diff --git a/package-lock.json b/package-lock.json index 531c663f59..4ed0f0c55c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-flow", - "version": "3.5.69", + "version": "3.5.71", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "claude-flow", - "version": "3.5.69", + "version": "3.5.71", "license": "MIT", "dependencies": { "semver": "^7.6.0", diff --git a/package.json b/package.json index 6ee058429b..7e2d89238b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-flow", - "version": "3.5.69", + "version": "3.5.71", "description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration", "main": "dist/index.js", "type": "module", diff --git a/ruflo/package.json b/ruflo/package.json index db41f16906..0c0906aeab 100644 --- a/ruflo/package.json +++ b/ruflo/package.json @@ -1,6 +1,6 @@ { "name": "ruflo", - "version": "3.5.69", + "version": "3.5.71", "description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration", "main": "bin/ruflo.js", "type": "module", diff --git a/v3/@claude-flow/cli/README.md b/v3/@claude-flow/cli/README.md index e2f02e419e..bd65d975fa 100644 --- a/v3/@claude-flow/cli/README.md +++ b/v3/@claude-flow/cli/README.md @@ -20,8 +20,8 @@ [![LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-0A66C2?style=for-the-badge&logo=linkedin)](https://www.linkedin.com/in/reuvencohen/) [![YouTube](https://img.shields.io/badge/YouTube-Subscribe-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://www.youtube.com/@ReuvenCohen) -# **Production-ready multi-agent AI orchestration for Claude Code** -*Deploy 100+ specialized agents in coordinated swarms with self-learning capabilities, fault-tolerant consensus, and enterprise-grade security.* +# **Multi-agent AI orchestration for Claude Code** +*Deploy 16 specialized agent roles + custom types in coordinated swarms with self-learning capabilities, fault-tolerant consensus, and enterprise-grade security.* @@ -62,7 +62,7 @@ flowchart TB subgraph SWARM["🐝 Swarm Coordination"] TOPO[Topologies
mesh/hier/ring/star] - CONS[Consensus
Raft/BFT/Gossip/CRDT] + CONS[Consensus
Raft/BFT/Gossip] CLM[Claims
Human-Agent Coord] end @@ -89,12 +89,12 @@ flowchart TB FLASH[Flash Attention
2.49-7.47x] end subgraph ROW2[" "] - HNSW[HNSW
150x-12,500x faster] + HNSW[HNSW
HNSW-indexed] RB[ReasoningBank
Pattern Store] HYP[Hyperbolic
PoincarΓ©] end subgraph ROW3[" "] - LORA[LoRA/Micro
128x compress] + LORA[LoRA/Micro
low-rank adaptation] QUANT[Int8 Quant
3.92x memory] RL[9 RL Algos
Q/SARSA/PPO/DQN] end @@ -130,7 +130,7 @@ flowchart TB | Component | Purpose | Performance | |-----------|---------|-------------| -| **SONA** | Self-Optimizing Neural Architecture - learns optimal routing | Fast adaptation | +| **SONA** | Self-Optimizing Pattern Learning - learns optimal routing | Fast adaptation | | **EWC++** | Elastic Weight Consolidation - prevents catastrophic forgetting | Preserves learned patterns | | **Flash Attention** | Optimized attention computation | 2-7x speedup (benchmarked) | | **HNSW** | Hierarchical Navigable Small World vector search | Sub-millisecond retrieval | @@ -230,8 +230,8 @@ The system stores successful patterns in vector memory, builds a knowledge graph | Knowledge Graph | MemoryGraph, PageRank, Communities | Identifies influential insights, detects clusters (ADR-049) | | Self-Learning | LearningBridge, SONA, ReasoningBank | Triggers learning from insights, confidence lifecycle (ADR-049) | | Agent Scopes | AgentMemoryScope, 3-scope dirs | Per-agent isolation + cross-agent knowledge transfer (ADR-049) | -| Embeddings | ONNX Runtime, MiniLM | Local vectors without API calls (75x faster) | -| Learning | SONA, MoE, ReasoningBank | Self-improves from results (<0.05ms adaptation) | +| Embeddings | ONNX Runtime, MiniLM | Local vectors without API calls (faster with ONNX runtime) | +| Learning | SONA, MoE, ReasoningBank | Self-improves from results (sub-millisecond pattern matching) | | Fine-tuning | MicroLoRA, EWC++ | Lightweight adaptation without full retraining | @@ -299,7 +299,7 @@ When you see these in hook output, the system is telling you how to optimize: ```bash # Agent Booster available - skip LLM entirely [AGENT_BOOSTER_AVAILABLE] Intent: var-to-const -β†’ Use Edit tool directly, 352x faster than LLM +β†’ Use Edit tool directly, instant (regex-based, no LLM call) than LLM # Model recommendation for Task tool [TASK_MODEL_RECOMMENDATION] Use model="haiku" @@ -312,12 +312,12 @@ When you see these in hook output, the system is telling you how to optimize: |--------|---------------|----------| | Latency | <1ms | 2-5s | | Cost | $0 | $0.0002-$0.015 | -| Speedup | **352x faster** | baseline | +| Speedup | **instant (regex-based, no LLM call)** | baseline |
-πŸ’° Token Optimizer β€” 30-50% token reduction +πŸ’° Token Optimizer β€” reduces token usage via pattern caching and smart routing The Token Optimizer integrates agentic-flow optimizations to reduce API costs by compressing context and caching results. @@ -340,7 +340,7 @@ const optimizer = await getTokenOptimizer(); // Get compact context (32% fewer tokens) const ctx = await optimizer.getCompactContext("auth patterns"); -// Optimized edit (352x faster for simple transforms) +// Optimized edit (instant (regex-based, no LLM call) for simple transforms) await optimizer.optimizedEdit(file, oldStr, newStr, "typescript"); // Optimal config for swarm (100% success rate) @@ -399,19 +399,19 @@ swarm_init({ | Capability | Claude Code Alone | Claude Code + Ruflo | |------------|-------------------|---------------------------| | **Agent Collaboration** | Agents work in isolation, no shared context | Agents collaborate via swarms with shared memory and consensus | -| **Coordination** | Manual orchestration between tasks | Queen-led hierarchy with 5 consensus algorithms (Raft, Byzantine, Gossip) | +| **Coordination** | Manual orchestration between tasks | Queen-led hierarchy with 3 consensus algorithms (Raft, Byzantine, Gossip) | | **Hive Mind** | β›” Not available | 🐝 Queen-led swarms with collective intelligence, 3 queen types, 8 worker types | | **Consensus** | β›” No multi-agent decisions | Byzantine fault-tolerant voting (f < n/3), weighted, majority | | **Memory** | Session-only, no persistence | HNSW vector memory with sub-ms retrieval + knowledge graph | | **Vector Database** | β›” No native support | 🐘 RuVector PostgreSQL with 77+ SQL functions, ~61Β΅s search, 16,400 QPS | | **Knowledge Graph** | β›” Flat insight lists | PageRank + community detection identifies influential insights (ADR-049) | | **Collective Memory** | β›” No shared knowledge | Shared knowledge base with LRU cache, SQLite persistence, 8 memory types | -| **Learning** | Static behavior, no adaptation | SONA self-learning with <0.05ms adaptation, LearningBridge for insights | +| **Learning** | Static behavior, no adaptation | SONA self-learning with sub-millisecond pattern matching, LearningBridge for insights | | **Agent Scoping** | Single project scope | 3-scope agent memory (project/local/user) with cross-agent transfer | | **Task Routing** | You decide which agent to use | Intelligent routing based on learned patterns (89% accuracy) | | **Complex Tasks** | Manual breakdown required | Automatic decomposition across 5 domains (Security, Core, Integration, Support) | | **Background Workers** | Nothing runs automatically | 12 context-triggered workers auto-dispatch on file changes, patterns, sessions | -| **LLM Provider** | Anthropic only | 6 providers with automatic failover and cost-based routing (85% savings) | +| **LLM Provider** | Anthropic only | 5 providers (Anthropic, OpenAI, Google, Cohere, Ollama) with automatic failover and cost-based routing (cost-optimized routing) | | **Security** | Standard protections | CVE-hardened with bcrypt, input validation, path traversal prevention | | **Performance** | Baseline | Faster tasks via parallel swarm spawning and intelligent routing | @@ -726,7 +726,7 @@ Ruflo v3 introduces **self-learning neural capabilities** that no other agent or | **Pattern Learning** | βœ… From trajectories | β›” | β›” | β›” | β›” | | **Expert Routing** | βœ… MoE (8 experts) | Manual | Graph edges | β›” | Fixed | | **Attention Optimization** | βœ… Flash Attention | β›” | β›” | β›” | β›” | -| **Low-Rank Adaptation** | βœ… LoRA (128x compress) | β›” | β›” | β›” | β›” | +| **Low-Rank Adaptation** | βœ… LoRA (low-rank adaptation) | β›” | β›” | β›” | β›” | #### πŸ’Ύ Memory & Embeddings @@ -783,7 +783,7 @@ What makes Ruflo different from other agent frameworks? These 10 capabilities wo | | Feature | What It Does | Technical Details | |---|---------|--------------|-------------------| -| 🧠 | **SONA** | Learns which agents perform best for each task type and routes work accordingly | Self-Optimizing Neural Architecture | +| 🧠 | **SONA** | Learns which agents perform best for each task type and routes work accordingly | Self-Optimizing Pattern Learning | | πŸ”’ | **EWC++** | Preserves learned patterns when training on new ones β€” no forgetting | Elastic Weight Consolidation prevents catastrophic forgetting | | 🎯 | **MoE** | Routes tasks through 8 specialized expert networks based on task type | Mixture of 8 Experts with dynamic gating | | ⚑ | **Flash Attention** | Accelerates attention computation for faster agent responses | Optimized attention via @ruvector/attention | @@ -797,7 +797,7 @@ What makes Ruflo different from other agent frameworks? These 10 capabilities wo
-πŸ’° Intelligent 3-Tier Model Routing β€” Save 75% on API costs, extend Claude Max 2.5x +πŸ’° Intelligent 3-Tier Model Routing β€” Reduce API costs by routing simple tasks to cheaper models Not every task needs the most powerful (and expensive) model. Ruflo analyzes each request and automatically routes it to the cheapest handler that can do the job well. Simple code transforms skip the LLM entirely using WebAssembly. Medium tasks use faster, cheaper models. Only complex architecture decisions use Opus. @@ -806,7 +806,7 @@ Not every task needs the most powerful (and expensive) model. Ruflo analyzes eac | Benefit | Impact | |---------|--------| | πŸ’΅ **API Cost Reduction** | 75% lower costs by using right-sized models | -| ⏱️ **Claude Max Extension** | 2.5x more tasks within your quota limits | +| ⏱️ **Claude Max Extension** | More tasks within quota via smart model selection | | πŸš€ **Faster Simple Tasks** | <1ms for transforms vs 2-5s with LLM | | 🎯 **Zero Wasted Tokens** | Simple edits use 0 tokens (WASM handles them) | @@ -818,7 +818,7 @@ Not every task needs the most powerful (and expensive) model. Ruflo analyzes eac | **2** | Haiku/Sonnet | 500ms-2s | $0.0002-$0.003 | Bug fixes, refactoring, feature implementation | | **3** | Opus | 2-5s | $0.015 | Architecture, security design, distributed systems | -**Benchmark Results:** 100% routing accuracy, 0.57ms avg routing decision latency +**Routing:** Q-learning with epsilon-greedy exploration, sub-millisecond decision latency
@@ -1563,7 +1563,7 @@ Comprehensive capabilities for enterprise-grade AI agent orchestration. Comprehensive feature set for enterprise-grade AI agent orchestration.
-πŸ€– Agent Ecosystem β€” 100+ specialized agents across 8 categories +πŸ€– Agent Ecosystem β€” 16 specialized agent roles + custom types across 8 categories Pre-built agents for every development task, from coding to security audits. @@ -1785,7 +1785,7 @@ Install these optional plugins to extend Ruflo capabilities: |--------|---------|-------------|-----------------| | **@claude-flow/plugin-agentic-qe** | 3.0.0-alpha.2 | Quality Engineering with 58 AI agents across 12 DDD contexts. TDD, coverage analysis, security scanning, chaos engineering, accessibility testing. | `npm install @claude-flow/plugin-agentic-qe` | | **@claude-flow/plugin-prime-radiant** | 0.1.4 | Mathematical AI interpretability with 6 engines: sheaf cohomology, spectral analysis, causal inference, quantum topology, category theory, HoTT proofs. | `npm install @claude-flow/plugin-prime-radiant` | -| **@claude-flow/plugin-gastown-bridge** | 0.1.0 | Gas Town orchestrator integration with WASM-accelerated formula parsing (352x faster), Beads sync, convoy management, and graph analysis. 20 MCP tools. | `npx ruflo@latest plugins install -n @claude-flow/plugin-gastown-bridge` | +| **@claude-flow/plugin-gastown-bridge** | 0.1.0 | Gas Town orchestrator integration with WASM-accelerated formula parsing (instant (regex-based, no LLM call)), Beads sync, convoy management, and graph analysis. 20 MCP tools. | `npx ruflo@latest plugins install -n @claude-flow/plugin-gastown-bridge` | | **@claude-flow/teammate-plugin** | 1.0.0-alpha.1 | Native TeammateTool integration for Claude Code v2.1.19+. BMSSP WASM acceleration, rate limiting, circuit breaker, semantic routing. 21 MCP tools. | `npx ruflo@latest plugins install -n @claude-flow/teammate-plugin` | #### πŸ₯ Domain-Specific Plugins @@ -1830,7 +1830,7 @@ Install these optional plugins to extend Ruflo capabilities: **Teammate Plugin Features:** - Native TeammateTool integration for Claude Code v2.1.19+ - 21 MCP tools: `teammate/spawn`, `teammate/coordinate`, `teammate/broadcast`, `teammate/discover-teams`, `teammate/route-task`, etc. -- BMSSP WASM acceleration for topology optimization (352x faster) +- BMSSP WASM acceleration for topology optimization (instant (regex-based, no LLM call)) - Rate limiting with sliding window (configurable limits) - Circuit breaker for fault tolerance (closed/open/half-open states) - Semantic routing with skill-based teammate selection @@ -2051,7 +2051,7 @@ npx ruflo@latest worker status
-☁️ LLM Providers β€” 6 providers with automatic failover +☁️ LLM Providers β€” 5 providers (Anthropic, OpenAI, Google, Cohere, Ollama) with automatic failover | Provider | Models | Features | Cost | |----------|--------|----------|------| @@ -2105,7 +2105,7 @@ npx ruflo@latest worker status | **Byzantine (PBFT)** | Practical Byzantine Fault Tolerance | f < n/3 faulty nodes | ~100ms | Adversarial environments | | **Raft** | Leader-based log replication | f < n/2 failures | ~50ms | Strong consistency | | **Gossip** | Epidemic protocol dissemination | High partition tolerance | ~200ms | Eventually consistent | -| **CRDT** | Conflict-free Replicated Data Types | Strong eventual consistency | ~10ms | Concurrent updates | +| **CRDT** | Conflict-free Replicated Data Types (planned) | Strong eventual consistency | ~10ms | Concurrent updates | | **Quorum** | Configurable read/write quorums | Flexible | ~75ms | Tunable consistency |
@@ -2196,8 +2196,8 @@ npx ruflo@latest worker status | Component | Description | Performance | |-----------|-------------|-------------| | **AgenticFlowBridge** | agentic-flow@alpha integration | ADR-001 compliant | -| **SONA Adapter** | Learning system integration | <0.05ms adaptation | -| **Flash Attention** | Attention mechanism coordinator | 2.49x-7.47x speedup | +| **SONA Adapter** | Learning system integration | sub-millisecond pattern matching | +| **Flash Attention** | Attention mechanism coordinator | optimized attention (WASM-accelerated when available) | | **SDK Bridge** | Version negotiation, API compatibility | Auto-detection | | **Feature Flags** | Dynamic feature management | 9 configurable flags | | **Runtime Detection** | NAPI, WASM, JS auto-selection | Optimal performance | @@ -2244,7 +2244,7 @@ npx ruflo@latest worker status | Feature | Description | Performance | |---------|-------------|-------------| -| **SONA Learning** | Self-Optimizing Neural Architecture | <0.05ms adaptation | +| **SONA Learning** | Self-Optimizing Pattern Learning | sub-millisecond pattern matching | | **5 Learning Modes** | real-time, balanced, research, edge, batch | Mode-specific optimization | | **9 RL Algorithms** | PPO, A2C, DQN, Q-Learning, SARSA, Decision Transformer, etc. | Comprehensive RL | | **LoRA Integration** | Low-Rank Adaptation for efficient fine-tuning | Minimal memory overhead | @@ -2256,7 +2256,7 @@ npx ruflo@latest worker status |---------|-------------|-------------| | **Scalar Quantization** | Reduce vector precision for memory savings | 4x memory reduction | | **Product Quantization** | Compress vectors into codebooks | 8-32x memory reduction | -| **HNSW Indexing** | Hierarchical Navigable Small World graphs | 150x-12,500x faster search | +| **HNSW Indexing** | Hierarchical Navigable Small World graphs | HNSW-indexed search | | **LRU Caching** | Intelligent embedding cache with TTL | <1ms cache hits | | **Batch Processing** | Process multiple embeddings in single call | 10x throughput | | **Memory Compression** | Pattern distillation and pruning | 50-75% reduction | @@ -2388,9 +2388,9 @@ npx ruflo hive-mind status # Check status |---------|-------------|---------| | **ADR-001 Compliance** | Build on agentic-flow, don't duplicate | Eliminates 10,000+ duplicate lines | | **Core Foundation** | Use agentic-flow as the base layer | Unified architecture | -| **SONA Integration** | Seamless learning system connection | <0.05ms adaptation | -| **Flash Attention** | Optimized attention mechanisms | 2.49x-7.47x speedup | -| **AgentDB Bridge** | Vector storage integration | 150x-12,500x faster search | +| **SONA Integration** | Seamless learning system connection | sub-millisecond pattern matching | +| **Flash Attention** | Optimized attention mechanisms | optimized attention (WASM-accelerated when available) | +| **AgentDB Bridge** | Vector storage integration | HNSW-indexed search | | **Feature Flags** | Dynamic capability management | 9 configurable features | | **Runtime Detection** | NAPI/WASM/JS auto-selection | Optimal performance per platform | | **Graceful Fallback** | Works with or without agentic-flow | Always functional | @@ -2678,7 +2678,7 @@ Complete command-line interface for all Ruflo operations. | `init` | 4 | Project initialization with wizard, presets, skills, hooks | | `agent` | 8 | Agent lifecycle (spawn, list, status, stop, metrics, pool, health, logs) | | `swarm` | 6 | Multi-agent swarm coordination and orchestration | -| `memory` | 11 | AgentDB memory with vector search (150x-12,500x faster) | +| `memory` | 11 | AgentDB memory with vector search (HNSW-indexed) | | `mcp` | 9 | MCP server management and tool execution | | `task` | 6 | Task creation, assignment, and lifecycle | | `session` | 7 | Session state management and persistence | @@ -2700,7 +2700,7 @@ Complete command-line interface for all Ruflo operations. | `providers` | 5 | AI providers (list, add, remove, test, configure) | | `plugins` | 5 | Plugin management (list, install, uninstall, enable, disable) | | `deployment` | 5 | Deployment management (deploy, rollback, status, environments, release) | -| `embeddings` | 4 | Vector embeddings (embed, batch, search, init) - 75x faster with agentic-flow | +| `embeddings` | 4 | Vector embeddings (embed, batch, search, init) - faster with ONNX runtime with agentic-flow | | `claims` | 4 | Claims-based authorization (check, grant, revoke, list) | | `migrate` | 5 | V2 to V3 migration with rollback support | | `process` | 4 | Background process management | @@ -2803,7 +2803,7 @@ The embeddings package (v3.0.0-alpha.12) provides high-performance vector embedd | **Document chunking** | Configurable overlap and size | Handles large documents | | **Normalization** | L2, L1, min-max, z-score | 4 normalization methods | | **Hyperbolic embeddings** | PoincarΓ© ball model | Better hierarchical representation | -| **agentic-flow ONNX** | Integrated ONNX runtime | 75x faster than API calls | +| **agentic-flow ONNX** | Integrated ONNX runtime | faster with ONNX runtime than API calls | | **Neural substrate** | RuVector integration | Full learning pipeline | **Models Available:** @@ -2994,7 +2994,7 @@ The statusline shows live context metrics read from `autopilot-state.json`: |------|---------|---------|----------| | 1 | **SQLite** (default) | `.claude-flow/data/transcript-archive.db` | WAL mode, indexed queries, ACID, importance ranking | | 2 | **RuVector PostgreSQL** | Configurable remote | TB-scale, pgvector embeddings, GNN search | -| 3 | **AgentDB + HNSW** | In-memory + persist | 150x-12,500x faster semantic search | +| 3 | **AgentDB + HNSW** | In-memory + persist | HNSW-indexed semantic search | | 4 | **JSON** (fallback) | `.claude-flow/data/transcript-archive.json` | Zero dependencies, always works | ### Configuration @@ -3202,7 +3202,7 @@ When hooks run, they emit signals that guide routing decisions. Watch for these | Signal | Meaning | Action | |--------|---------|--------| -| `[AGENT_BOOSTER_AVAILABLE]` | Simple transform detected, skip LLM | Use Edit tool directly (352x faster, $0) | +| `[AGENT_BOOSTER_AVAILABLE]` | Simple transform detected, skip LLM | Use Edit tool directly (instant (regex-based, no LLM call), $0) | | `[TASK_MODEL_RECOMMENDATION] Use model="haiku"` | Low complexity task | Pass `model: "haiku"` to Task tool | | `[TASK_MODEL_RECOMMENDATION] Use model="sonnet"` | Medium complexity task | Pass `model: "sonnet"` to Task tool | | `[TASK_MODEL_RECOMMENDATION] Use model="opus"` | High complexity task | Pass `model: "opus"` to Task tool | @@ -3221,7 +3221,7 @@ $ npx ruflo@latest hooks pre-task --description "convert var to const in utils.t [AGENT_BOOSTER_AVAILABLE] Intent: var-to-const Recommendation: Use Edit tool directly -Performance: <1ms (352x faster than LLM) +Performance: <1ms (instant (regex-based, no LLM call) than LLM) Cost: $0 ``` @@ -3243,7 +3243,7 @@ UserPrompt: β†’ Inject top-5 patterns into Claude's context: [INTELLIGENCE] Relevant patterns for this task: - * (0.95) HNSW gives 150x-12,500x speedup [rank #1, 12x accessed] + * (0.95) HNSW gives HNSW-indexed search [rank #1, 12x accessed] * (0.88) London School TDD preferred [rank #3, 8x accessed] PostEdit: @@ -3305,7 +3305,7 @@ The stats command shows: Never accessed: 3 Top Patterns (by composite score) - #1 HNSW gives 150x-12,500x speedup + #1 HNSW gives HNSW-indexed search conf=0.600 pr=0.2099 score=0.3659 accessed=2x #2 London School TDD preferred conf=0.600 pr=0.1995 score=0.3597 accessed=2x @@ -3686,7 +3686,7 @@ curl "https://publish-registry-xxx.cloudfunctions.net?action=import-model&cid=Qm ### Pre-trained Model Registry -Import pre-trained learning patterns for common tasks. **90.5% average accuracy** across 40 patterns trained on 110,600+ examples. +Import pre-defined rule-based patterns for common tasks. 40 patterns across 8 categories (trigger-action rules, not ML-trained models). | Model | Category | Patterns | Accuracy | Use Case | |-------|----------|----------|----------|----------| @@ -3720,8 +3720,8 @@ npx ruflo@latest hooks route --task "review authentication code" --use-patterns | Metric | Fresh Install | With Pre-trained | |--------|---------------|------------------| | Patterns Available | 0 | 40 | -| Detection Accuracy | ~50-60% | 90.5% | -| Historical Examples | 0 | 110,600+ | +| Detection Patterns | ~50-60% | 40 rule-based patterns | +| Pattern Categories | 0 | 8 categories | | Issue Detection Rate | ~60-70% | ~90-95% | | Time to First Insight | Discovery needed | Immediate | @@ -4050,8 +4050,8 @@ Skills are **reusable workflows** that combine agents, hooks, and patterns into |-------|--------------|-------------| | `v3-ddd-architecture` | Bounded contexts, modular design, clean architecture | Large-scale refactoring | | `v3-security-overhaul` | CVE fixes, secure-by-default patterns | Security hardening | -| `v3-memory-unification` | AgentDB unification, 150x-12,500x search improvements | Memory optimization | -| `v3-performance-optimization` | 2.49x-7.47x speedup, memory reduction | Performance tuning | +| `v3-memory-unification` | AgentDB unification, HNSW search improvements | Memory optimization | +| `v3-performance-optimization` | optimized attention (WASM-accelerated when available), memory reduction | Performance tuning | | `v3-swarm-coordination` | 15-agent hierarchical mesh, 10 ADRs implementation | Swarm architecture | | `v3-mcp-optimization` | Connection pooling, load balancing, <100ms response | MCP performance | | `v3-core-implementation` | DDD domains, dependency injection, TypeScript | Core development | @@ -4420,7 +4420,7 @@ npx ruflo@latest memory init --force npx ruflo@latest memory store --key "pattern-auth" --value "JWT authentication with refresh tokens" npx ruflo@latest memory store --key "pattern-cache" --value "Redis caching for API responses" -# Build HNSW index for 150x-12,500x faster search +# Build HNSW index for HNSW-indexed search npx ruflo@latest memory search --query "authentication" --build-hnsw # Semantic search (uses HNSW if built) @@ -4501,7 +4501,7 @@ await aidefence.learnFromDetection(userInput, analysis, { | Provider | Latency | Quality | Cost | Offline | Best For | |----------|---------|---------|------|---------|----------| -| **Agentic-Flow (ONNX)** | ~3ms | Good | Free | βœ… | Production (75x faster) | +| **Agentic-Flow (ONNX)** | ~3ms | Good | Free | βœ… | Production (faster with ONNX runtime) | | **OpenAI** | ~50-100ms | Excellent | $0.02-0.13/1M | ❌ | Highest quality | | **Transformers.js** | ~230ms | Good | Free | βœ… | Local development | | **Mock** | <1ms | N/A | Free | βœ… | Testing | @@ -4766,7 +4766,7 @@ Core infrastructure packages powering Ruflo's intelligence layer. [![npm downloads](https://img.shields.io/npm/dm/agentic-flow?color=green)](https://www.npmjs.com/package/agentic-flow) [![GitHub](https://img.shields.io/badge/GitHub-ruvnet%2Fagentic--flow-blue?logo=github)](https://github.com/ruvnet/agentic-flow) -Ruflo v3 is built on top of **[agentic-flow](https://github.com/ruvnet/agentic-flow)**, a production-ready AI agent orchestration platform. This deep integration provides 352x faster code transformations, learning memory, and geometric intelligence. +Ruflo v3 is built on top of **[agentic-flow](https://github.com/ruvnet/agentic-flow)**, a production-ready AI agent orchestration platform. This deep integration provides instant (regex-based, no LLM call) code transformations, learning memory, and geometric intelligence. ### Quick Start @@ -4788,9 +4788,9 @@ claude mcp add agentic-flow -- npx agentic-flow mcp start | Component | Description | Performance | |-----------|-------------|-------------| -| **Agent Booster** | Rust/WASM code transformations | 352x faster, $0 cost | -| **ReasoningBank** | Learning memory with HNSW | 150x-12,500x search | -| **ONNX Embeddings** | Local vector generation | 75x faster than Transformers.js | +| **Agent Booster** | Rust/WASM code transformations | instant (regex-based, no LLM call), $0 cost | +| **ReasoningBank** | Learning memory with HNSW | HNSW-indexed search | +| **ONNX Embeddings** | Local vector generation | faster with ONNX runtime than Transformers.js | | **Embedding Geometry** | Geometric intelligence layer | <3ms latency | | **Multi-Model Router** | Intelligent model selection | 30-50% cost savings | | **QUIC Transport** | High-performance transport | Ultra-low latency | @@ -5025,7 +5025,7 @@ npx agentic-flow mcp stdio
πŸ”§ MCP Tools β€” 313 Integration Tools -Agentic-flow exposes 310+ MCP tools for integration: +The agentic-flow ecosystem exposes MCP tools across packages (ruflo CLI provides 314 tools): | Category | Tools | Examples | |----------|-------|----------| @@ -5068,7 +5068,7 @@ const optimizer = await getTokenOptimizer(); // Uses ReasoningBank (32% fewer tokens) const ctx = await optimizer.getCompactContext('auth patterns'); -// Uses Agent Booster (352x faster edits) +// Uses Agent Booster (instant (regex-based, no LLM call) edits) await optimizer.optimizedEdit(file, old, new, 'typescript'); // Uses Model Router (optimal model selection) @@ -5197,7 +5197,7 @@ console.log('All agents completed:', results); |--------|-----|-----------------| | Concurrent commits | 15 ops/s | **350 ops/s (23x)** | | Context switching | 500-1000ms | **50-100ms (10x)** | -| Conflict resolution | 30-40% auto | **87% auto (2.5x)** | +| Conflict resolution | 30-40% auto | **AI-assisted (via agentic-jujutsu)** | | Lock waiting | 50 min/day | **0 min (∞)** | | SHA3-512 fingerprints | N/A | **<1ms** | @@ -5494,7 +5494,7 @@ console.log(`Memory reduction: ${bench.memoryReduction}x`);
-🧠 @ruvector/sona β€” Self-Optimizing Neural Architecture +🧠 @ruvector/sona β€” Self-Optimizing Pattern Learning SONA provides runtime-adaptive learning with minimal overhead: @@ -5531,7 +5531,7 @@ await sona.consolidate(); - **LoRA**: Low-rank adaptation for efficient fine-tuning - **EWC++**: Prevents catastrophic forgetting - **ReasoningBank**: Pattern storage with similarity search -- **Sub-millisecond**: <0.05ms adaptation overhead +- **Sub-millisecond**: sub-millisecond pattern matching overhead
@@ -6403,7 +6403,7 @@ Statistical benchmarking, memory tracking, regression detection, and V3 performa | **Auto-Calibration** | Adjusts iterations for statistical significance | Automatic | | **Regression Detection** | Compare against baselines with significance testing | <10ms | | **V3 Targets** | Built-in targets for all performance metrics | Preconfigured | -| **Flash Attention** | Validate 2.49x-7.47x speedup targets | Integrated | +| **Flash Attention** | Validate optimized attention (WASM-accelerated when available) targets | Integrated | ### Quick Start @@ -7349,7 +7349,7 @@ export CLAUDE_FLOW_HNSW_EF=100 β”‚ Pattern Matching β”‚ Self-learning (ReasoningBank) β”‚ β”‚ Security β”‚ CVE remediation + strict validation β”‚ β”‚ Modular Architecture β”‚ 18 @claude-flow/* packages β”‚ -β”‚ Agent Coordination β”‚ 100+ specialized agents β”‚ +β”‚ Agent Coordination β”‚ 16 specialized agent roles + custom types β”‚ β”‚ Token Efficiency β”‚ 32% reduction with optimization β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` diff --git a/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts b/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts index ac2ab03cb8..92728a387e 100644 --- a/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts +++ b/v3/@claude-flow/cli/__tests__/mcp-tools-deep.test.ts @@ -788,7 +788,7 @@ describe('MCP Tools Deep Test Suite', () => { const tool = githubTools.find(t => t.name === 'github_repo_analyze')!; const result: any = await tool.handler({}); expect(result.success).toBe(true); - expect(result.analysis).toBeDefined(); + expect(result.repository).toBeDefined(); }); it('github_pr_manage list returns PRs', async () => { @@ -801,7 +801,7 @@ describe('MCP Tools Deep Test Suite', () => { const tool = githubTools.find(t => t.name === 'github_metrics')!; const result: any = await tool.handler({}); expect(result.success).toBe(true); - expect(result.metrics).toBeDefined(); + expect(result.commits).toBeDefined(); }); }); @@ -915,13 +915,13 @@ describe('MCP Tools Deep Test Suite', () => { const tool = agentdbTools.find(t => t.name === 'agentdb_pattern-store')!; const result: any = await tool.handler({}); expect(result.success).toBe(false); - expect(result.error).toContain('pattern is required'); + expect(result.error).toMatch(/pattern.*(required|must be)/i); }); it('agentdb_pattern-search requires query param', async () => { const tool = agentdbTools.find(t => t.name === 'agentdb_pattern-search')!; const result: any = await tool.handler({}); - expect(result.error).toContain('query is required'); + expect(result.error).toMatch(/query.*(required|must be)/i); }); it('agentdb_causal-edge validates required fields', async () => { @@ -933,7 +933,7 @@ describe('MCP Tools Deep Test Suite', () => { it('agentdb_route requires task param', async () => { const tool = agentdbTools.find(t => t.name === 'agentdb_route')!; const result: any = await tool.handler({}); - expect(result.error).toContain('task is required'); + expect(result.error).toMatch(/task.*(required|must be)/i); }); it('agentdb_batch validates entries array', async () => { diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json index c814041e36..8fb0ef825f 100644 --- a/v3/@claude-flow/cli/package.json +++ b/v3/@claude-flow/cli/package.json @@ -1,6 +1,6 @@ { "name": "@claude-flow/cli", - "version": "3.5.69", + "version": "3.5.71", "type": "module", "description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code", "main": "dist/src/index.js", diff --git a/v3/@claude-flow/cli/src/commands/autopilot.ts b/v3/@claude-flow/cli/src/commands/autopilot.ts index d6a8efea12..6fed1ed891 100644 --- a/v3/@claude-flow/cli/src/commands/autopilot.ts +++ b/v3/@claude-flow/cli/src/commands/autopilot.ts @@ -254,8 +254,8 @@ const learnCommand: Command = { return { success: true }; } - const metrics = await (learning as any).getMetrics(); - const patterns = await (learning as any).discoverSuccessPatterns(); + const metrics = await (learning as unknown as { getMetrics: () => Promise<{ episodes: number; patterns: number; trajectories: number }> }).getMetrics(); + const patterns = await (learning as unknown as { discoverSuccessPatterns: () => Promise> }).discoverSuccessPatterns(); if (ctx.flags?.json) { output.printJson({ metrics, patterns }); @@ -299,7 +299,7 @@ const historyCommand: Command = { return { success: true }; } - const results = await (learning as any).recallSimilarTasks(query, limit); + const results = await (learning as unknown as { recallSimilarTasks: (query: string, limit: number) => Promise }).recallSimilarTasks(query, limit); if (ctx.flags?.json) { output.printJson(results); } else if (results.length === 0) { @@ -320,13 +320,13 @@ const predictCommand: Command = { const learning = await tryLoadLearning(); if (learning) { - const prediction = await (learning as any).predictNextAction(state); + const prediction = await (learning as unknown as { predictNextAction: (state: unknown) => Promise<{ action?: string; confidence?: number; alternatives?: string[] } | null> }).predictNextAction(state); if (ctx.flags?.json) { output.printJson(prediction); } else { output.writeln(`Action: ${prediction?.action || 'unknown'}`); output.writeln(`Confidence: ${prediction?.confidence || 0}`); - if (prediction?.alternatives?.length > 0) output.writeln(`Alternatives: ${prediction.alternatives.join(', ')}`); + if (prediction?.alternatives && prediction.alternatives.length > 0) output.writeln(`Alternatives: ${prediction.alternatives.join(', ')}`); } return { success: true }; } diff --git a/v3/@claude-flow/cli/src/commands/daemon.ts b/v3/@claude-flow/cli/src/commands/daemon.ts index 9ad8eca4be..05232781b9 100644 --- a/v3/@claude-flow/cli/src/commands/daemon.ts +++ b/v3/@claude-flow/cli/src/commands/daemon.ts @@ -65,7 +65,7 @@ const startCommand: Command = { } } if (thresholds.maxCpuLoad !== undefined || thresholds.minFreeMemoryPercent !== undefined) { - config.resourceThresholds = thresholds as any; + config.resourceThresholds = thresholds as DaemonConfig['resourceThresholds']; } } @@ -256,7 +256,7 @@ async function startBackgroundDaemon(projectRoot: string, quiet: boolean, maxCpu // Platform-aware spawn flags const isWin = process.platform === 'win32'; - const spawnOpts: any = { + const spawnOpts: Record = { cwd: resolvedRoot, detached: !isWin, // detached is POSIX-only; Windows uses windowsHide // Use 'ignore' for all stdio β€” passing fs.openSync() FDs causes the child to @@ -502,8 +502,8 @@ const statusCommand: Command = { const workerData = status.config.workers.map(w => { const state = status.workers.get(w.type); // Check for headless mode from worker config or state - const isHeadless = (w as any).headless || (state as any)?.headless || false; - const sandboxMode = (w as any).sandbox || (state as any)?.sandbox || null; + const isHeadless = (w as unknown as Record).headless || (state as unknown as Record | undefined)?.headless || false; + const sandboxMode = (w as unknown as Record).sandbox || (state as unknown as Record | undefined)?.sandbox || null; return { type: w.enabled ? output.highlight(w.type) : output.dim(w.type), enabled: w.enabled ? output.success('βœ“') : output.dim('β—‹'), diff --git a/v3/@claude-flow/cli/src/commands/guidance.ts b/v3/@claude-flow/cli/src/commands/guidance.ts index a9ddcc6a14..bb2b71afff 100644 --- a/v3/@claude-flow/cli/src/commands/guidance.ts +++ b/v3/@claude-flow/cli/src/commands/guidance.ts @@ -6,6 +6,17 @@ import type { Command, CommandContext, CommandResult } from '../types.js'; import { output } from '../output.js'; +/** Task intent categories matching @claude-flow/guidance TaskIntent */ +type TaskIntent = 'bug-fix' | 'feature' | 'refactor' | 'security' | 'performance' | 'testing' | 'docs' | 'deployment' | 'architecture' | 'debug' | 'general'; + +/** Gate evaluation result matching @claude-flow/guidance GateResult */ +interface GateResult { + decision: string; + gateName: string; + reason: string; + remediation?: string; +} + // compile subcommand const compileCommand: Command = { name: 'compile', @@ -145,7 +156,7 @@ const retrieveCommand: Command = { const result = await retriever.retrieve({ taskDescription: task, maxShards, - intent: intentOverride as any, + intent: intentOverride as TaskIntent | undefined, }); if (jsonOutput) { @@ -212,7 +223,7 @@ const gatesCommand: Command = { const { EnforcementGates } = await import('@claude-flow/guidance/gates'); const gates = new EnforcementGates(); - const results: Array<{ type: string; result: any }> = []; + const results: Array<{ type: string; result: GateResult[] | GateResult | null }> = []; if (command) { const gateResults = gates.evaluateCommand(command); diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.ts index 19bead0af8..6d5f4874ff 100644 --- a/v3/@claude-flow/cli/src/commands/hooks.ts +++ b/v3/@claude-flow/cli/src/commands/hooks.ts @@ -4468,7 +4468,7 @@ const postBashCommand: Command = { // Token Optimizer command - integrates agentic-flow Agent Booster const tokenOptimizeCommand: Command = { name: 'token-optimize', - description: 'Token optimization via agentic-flow Agent Booster (30-50% savings)', + description: 'Token optimization via agentic-flow Agent Booster integration', options: [ { name: 'query', short: 'q', type: 'string', description: 'Query for compact context retrieval' }, { name: 'agents', short: 'A', type: 'number', description: 'Agent count for optimal config', default: '6' }, @@ -4498,8 +4498,7 @@ const tokenOptimizeCommand: Command = { memoriesRetrieved: 0, }; let agenticFlowAvailable = false; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let reasoningBank: any = null; + let reasoningBank: { retrieveMemories: (query: string, opts: { k: number }) => Promise; formatMemoriesForPrompt?: (memories: unknown[]) => string } | null = null; try { // Check if agentic-flow v3 is available @@ -4558,10 +4557,8 @@ const tokenOptimizeCommand: Command = { output.printInfo('ReasoningBank not available - query skipped'); } - // Simulate some token savings for demo - stats.totalTokensSaved += 200; - stats.cacheHits = 2; - stats.cacheMisses = 1; + // Note: stats reflect only actual measured values from this session. + // No simulated/fabricated data is added. // Show stats if (showStats || showReport) { @@ -5210,7 +5207,7 @@ export const hooksCommand: Command = { `${output.highlight('coverage-route')} - Route tasks based on coverage gaps (ruvector)`, `${output.highlight('coverage-suggest')}- Suggest coverage improvements`, `${output.highlight('coverage-gaps')} - List all coverage gaps with agents`, - `${output.highlight('token-optimize')} - Token optimization (30-50% savings)`, + `${output.highlight('token-optimize')} - Token optimization (agentic-flow integration)`, `${output.highlight('model-route')} - Route to optimal model (haiku/sonnet/opus)`, `${output.highlight('model-outcome')} - Record model routing outcome`, `${output.highlight('model-stats')} - View model routing statistics`, diff --git a/v3/@claude-flow/cli/src/commands/init.ts b/v3/@claude-flow/cli/src/commands/init.ts index 6203c73355..368a5bc613 100644 --- a/v3/@claude-flow/cli/src/commands/init.ts +++ b/v3/@claude-flow/cli/src/commands/init.ts @@ -37,7 +37,14 @@ async function initCodexAction( try { // Dynamic import of the Codex initializer with lazy loading fallback - let CodexInitializer: any; + interface CodexInitResult { + success: boolean; + errors?: string[]; + filesCreated: string[]; + skillsGenerated: string[]; + warnings?: string[]; + } + let CodexInitializer: (new () => { initialize: (options: Record) => Promise }) | undefined; // Try multiple resolution strategies for the @claude-flow/codex package // Use a variable to prevent TypeScript from statically resolving the optional module diff --git a/v3/@claude-flow/cli/src/commands/mcp.ts b/v3/@claude-flow/cli/src/commands/mcp.ts index 3da6bd1218..fcf23c78b8 100644 --- a/v3/@claude-flow/cli/src/commands/mcp.ts +++ b/v3/@claude-flow/cli/src/commands/mcp.ts @@ -172,7 +172,7 @@ const startCommand: Command = { output.writeln(output.dim(' Loading tool registry...')); }); - manager.on('started', (data: any) => { + manager.on('started', (data: { startupTime?: number }) => { output.writeln(output.dim(` Server started in ${data.startupTime?.toFixed(2) || 0}ms`)); }); diff --git a/v3/@claude-flow/cli/src/commands/neural.ts b/v3/@claude-flow/cli/src/commands/neural.ts index 4c146e39bc..ecc09d2d1b 100644 --- a/v3/@claude-flow/cli/src/commands/neural.ts +++ b/v3/@claude-flow/cli/src/commands/neural.ts @@ -1574,7 +1574,8 @@ const benchmarkCommand: Command = { spinner.start(); try { - const attention: any = await import('@ruvector/attention'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic import of optional native WASM module with no type declarations + const attention = await import('@ruvector/attention') as unknown as Record { computeRaw: (q: Float32Array, k: Float32Array[], v: Float32Array[]) => Float32Array }>; // Manual benchmark since benchmarkAttention has a binding bug const benchmarkMechanism = async (name: string, mechanism: { computeRaw: (q: Float32Array, k: Float32Array[], v: Float32Array[]) => Float32Array }) => { diff --git a/v3/@claude-flow/cli/src/commands/plugins.ts b/v3/@claude-flow/cli/src/commands/plugins.ts index abaeb1ab1e..074685c1c2 100644 --- a/v3/@claude-flow/cli/src/commands/plugins.ts +++ b/v3/@claude-flow/cli/src/commands/plugins.ts @@ -17,6 +17,7 @@ import { getOfficialPlugins, type PluginEntry, type PluginSearchOptions, + type PluginType, } from '../plugins/store/index.js'; import { getPluginManager, type InstalledPlugin } from '../plugins/manager.js'; import { getBulkRatings } from '../services/registry-api.js'; @@ -113,7 +114,7 @@ const listCommand: Command = { // Build search options const searchOptions: PluginSearchOptions = { category, - type: type as any, + type: type as PluginType, sortBy: 'downloads', sortOrder: 'desc', }; @@ -768,7 +769,7 @@ const searchCommand: Command = { const searchOptions: PluginSearchOptions = { query, category, - type: type as any, + type: type as PluginType, verified, limit, sortBy: 'downloads', diff --git a/v3/@claude-flow/cli/src/commands/providers.ts b/v3/@claude-flow/cli/src/commands/providers.ts index d9becc51d1..db7e9a9acd 100644 --- a/v3/@claude-flow/cli/src/commands/providers.ts +++ b/v3/@claude-flow/cli/src/commands/providers.ts @@ -9,6 +9,115 @@ import type { Command, CommandContext, CommandResult } from '../types.js'; import { output } from '../output.js'; import { configManager } from '../services/config-file-manager.js'; +/** Static provider catalog used as a reference/fallback */ +interface ProviderCatalogEntry { + name: string; + type: string; + models: string; + envVar?: string; + configName?: string; +} + +const PROVIDER_CATALOG: ProviderCatalogEntry[] = [ + { name: 'Anthropic', type: 'LLM', models: 'claude-3.5-sonnet, opus', envVar: 'ANTHROPIC_API_KEY', configName: 'anthropic' }, + { name: 'OpenAI', type: 'LLM', models: 'gpt-4o, gpt-4-turbo', envVar: 'OPENAI_API_KEY', configName: 'openai' }, + { name: 'OpenAI', type: 'Embedding', models: 'text-embedding-3-small/large', envVar: 'OPENAI_API_KEY', configName: 'openai' }, + { name: 'Google', type: 'LLM', models: 'gemini-pro, gemini-ultra', envVar: 'GOOGLE_API_KEY', configName: 'google' }, + { name: 'Transformers.js', type: 'Embedding', models: 'Xenova/all-MiniLM-L6-v2' }, + { name: 'Agentic Flow', type: 'Embedding', models: 'ONNX optimized' }, + { name: 'Mock', type: 'All', models: 'mock-*' }, +]; + +/** + * Resolve the API key for a provider by checking the config file first, + * then falling back to well-known environment variables. + */ +function resolveApiKey( + providerName: string, + configuredProviders: Array>, +): string | undefined { + // Check config file entry + const entry = configuredProviders.find( + (p) => typeof p.name === 'string' && p.name.toLowerCase() === providerName.toLowerCase(), + ); + if (entry?.apiKey && typeof entry.apiKey === 'string') { + return entry.apiKey; + } + + // Check environment variable + const envMapping: Record = { + anthropic: 'ANTHROPIC_API_KEY', + openai: 'OPENAI_API_KEY', + google: 'GOOGLE_API_KEY', + }; + const envVar = envMapping[providerName.toLowerCase()]; + if (envVar && process.env[envVar]) { + return process.env[envVar]; + } + + return undefined; +} + +/** + * Make a lightweight HTTP request to verify provider API key validity. + * Uses a 5-second timeout. Returns { ok, reason }. + */ +async function testProviderConnectivity( + providerName: string, + apiKey: string, +): Promise<{ ok: boolean; reason: string }> { + const endpoints: Record }> = { + anthropic: { + url: 'https://api.anthropic.com/v1/models', + headers: { + 'x-api-key': apiKey, + 'anthropic-version': '2023-06-01', + }, + }, + openai: { + url: 'https://api.openai.com/v1/models', + headers: { + 'Authorization': `Bearer ${apiKey}`, + }, + }, + google: { + url: `https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`, + headers: {}, + }, + }; + + const endpointConfig = endpoints[providerName.toLowerCase()]; + if (!endpointConfig) { + return { ok: false, reason: 'No test endpoint available for this provider' }; + } + + try { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 5000); + const res = await fetch(endpointConfig.url, { + method: 'GET', + headers: endpointConfig.headers, + signal: controller.signal, + }); + clearTimeout(timeout); + + if (res.ok || res.status === 200) { + return { ok: true, reason: 'Connected successfully' }; + } + if (res.status === 401 || res.status === 403) { + return { ok: false, reason: `Authentication failed (HTTP ${res.status})` }; + } + // A non-auth error but the server responded β€” key format may be fine + return { ok: false, reason: `Unexpected response (HTTP ${res.status})` }; + } catch (err: unknown) { + if (err instanceof Error && err.name === 'AbortError') { + return { ok: false, reason: 'Connection timed out (5s)' }; + } + const msg = err instanceof Error ? err.message : String(err); + return { ok: false, reason: `Connection failed: ${msg}` }; + } +} + // List subcommand const listCommand: Command = { name: 'list', @@ -23,28 +132,98 @@ const listCommand: Command = { ], action: async (ctx: CommandContext): Promise => { const type = ctx.flags.type as string || 'all'; + const activeOnly = ctx.flags.active as boolean; + + // Load user configuration + const cwd = process.cwd(); + const config = configManager.getConfig(cwd); + const agents = (config.agents ?? {}) as Record; + const configuredProviders = (agents.providers ?? []) as Array>; + + // Build table rows from the catalog, enriched with configuration status + const rows: Array> = []; + + for (const entry of PROVIDER_CATALOG) { + // Apply type filter + if (type !== 'all' && entry.type.toLowerCase() !== type.toLowerCase()) { + continue; + } + + let status: string; + let keySource = ''; + + if (entry.configName) { + const apiKey = resolveApiKey(entry.configName, configuredProviders); + if (apiKey) { + // Determine the source for the key + const configEntry = configuredProviders.find( + (p) => typeof p.name === 'string' && p.name.toLowerCase() === entry.configName!.toLowerCase(), + ); + if (configEntry?.apiKey && typeof configEntry.apiKey === 'string') { + keySource = 'config'; + } else { + keySource = 'env'; + } + status = output.success(`Configured (${keySource})`); + } else { + status = output.warning('Not configured'); + } + } else if (entry.name === 'Mock') { + status = output.dim('Dev only'); + } else { + // Local-only providers (Transformers.js, Agentic Flow) β€” always available + status = output.success('Available (local)'); + } + + if (activeOnly && !status.includes('Configured') && !status.includes('Available')) { + continue; + } + + rows.push({ + provider: entry.name, + type: entry.type, + models: entry.models, + status, + }); + } + + // Also show any providers in config that are not in the static catalog + for (const cp of configuredProviders) { + const cpName = (cp.name as string) || ''; + const alreadyListed = PROVIDER_CATALOG.some( + (e) => e.configName?.toLowerCase() === cpName.toLowerCase() || e.name.toLowerCase() === cpName.toLowerCase(), + ); + if (!alreadyListed && cpName) { + const hasKey = !!(cp.apiKey || resolveApiKey(cpName, configuredProviders)); + rows.push({ + provider: cpName, + type: (cp.type as string) || 'Custom', + models: (cp.model as string) || output.dim('(not specified)'), + status: hasKey ? output.success('Configured (config)') : output.warning('Not configured'), + }); + } + } - // Note: Static provider catalog β€” does not reflect user's configured providers output.writeln(); - output.writeln(output.bold('Available Providers')); + output.writeln(output.bold('Providers')); output.writeln(output.dim('─'.repeat(60))); - output.printTable({ - columns: [ - { key: 'provider', header: 'Provider', width: 18 }, - { key: 'type', header: 'Type', width: 12 }, - { key: 'models', header: 'Models', width: 25 }, - { key: 'status', header: 'Status', width: 12 }, - ], - data: [ - { provider: 'Anthropic', type: 'LLM', models: 'claude-3.5-sonnet, opus', status: output.success('Active') }, - { provider: 'OpenAI', type: 'LLM', models: 'gpt-4o, gpt-4-turbo', status: output.success('Active') }, - { provider: 'OpenAI', type: 'Embedding', models: 'text-embedding-3-small/large', status: output.success('Active') }, - { provider: 'Transformers.js', type: 'Embedding', models: 'Xenova/all-MiniLM-L6-v2', status: output.success('Active') }, - { provider: 'Agentic Flow', type: 'Embedding', models: 'ONNX optimized', status: output.success('Active') }, - { provider: 'Mock', type: 'All', models: 'mock-*', status: output.dim('Dev only') }, - ], - }); + if (rows.length === 0) { + output.writeln(output.dim(' No providers match the current filter.')); + } else { + output.printTable({ + columns: [ + { key: 'provider', header: 'Provider', width: 18 }, + { key: 'type', header: 'Type', width: 12 }, + { key: 'models', header: 'Models', width: 25 }, + { key: 'status', header: 'Status', width: 20 }, + ], + data: rows, + }); + } + + output.writeln(); + output.writeln(output.dim('Tip: Use "providers configure -p -k " to set API keys.')); return { success: true }; }, @@ -149,107 +328,96 @@ const testCommand: Command = { const agents = (config.agents ?? {}) as Record; const configuredProviders = (agents.providers ?? []) as Array>; - // Build list of providers to test - interface ProviderCheck { + // Collect the set of providers to test + interface ProviderTestTarget { name: string; - test: () => Promise<{ pass: boolean; reason: string }>; + configName: string; } - const getConfigApiKey = (name: string): string | undefined => { - const entry = configuredProviders.find( - (p) => typeof p.name === 'string' && p.name.toLowerCase() === name.toLowerCase(), - ); - return entry?.apiKey as string | undefined; - }; - - const knownChecks: ProviderCheck[] = [ - { - name: 'Anthropic', - test: async () => { - const key = process.env.ANTHROPIC_API_KEY || getConfigApiKey('anthropic'); - if (key) return { pass: true, reason: 'API key found' }; - return { pass: false, reason: 'ANTHROPIC_API_KEY not set and no apiKey in config' }; - }, - }, - { - name: 'OpenAI', - test: async () => { - const key = process.env.OPENAI_API_KEY || getConfigApiKey('openai'); - if (key) return { pass: true, reason: 'API key found' }; - return { pass: false, reason: 'OPENAI_API_KEY not set and no apiKey in config' }; - }, - }, - { - name: 'Google', - test: async () => { - const key = process.env.GOOGLE_API_KEY || getConfigApiKey('google'); - if (key) return { pass: true, reason: 'API key found' }; - return { pass: false, reason: 'GOOGLE_API_KEY not set and no apiKey in config' }; - }, - }, - { - name: 'Ollama', - test: async () => { - const entry = configuredProviders.find( - (p) => typeof p.name === 'string' && p.name.toLowerCase() === 'ollama', - ); - const baseUrl = (entry?.baseUrl as string) || 'http://localhost:11434'; - try { - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), 3000); - const res = await fetch(baseUrl, { signal: controller.signal }); - clearTimeout(timeout); - if (res.ok) return { pass: true, reason: `Reachable at ${baseUrl}` }; - return { pass: false, reason: `HTTP ${res.status} from ${baseUrl}` }; - } catch { - return { pass: false, reason: `Unreachable at ${baseUrl}` }; - } - }, - }, + const knownTargets: ProviderTestTarget[] = [ + { name: 'Anthropic', configName: 'anthropic' }, + { name: 'OpenAI', configName: 'openai' }, + { name: 'Google', configName: 'google' }, ]; - // Filter to requested provider or test all - let checksToRun: ProviderCheck[]; + // Add Ollama as a special case (endpoint-based, no API key) + const ollamaEntry = configuredProviders.find( + (p) => typeof p.name === 'string' && p.name.toLowerCase() === 'ollama', + ); + + let targets: ProviderTestTarget[]; if (testAll || !provider) { - checksToRun = knownChecks; + targets = [...knownTargets]; } else { - const match = knownChecks.find( - (c) => c.name.toLowerCase() === provider.toLowerCase(), + const match = knownTargets.find( + (t) => t.name.toLowerCase() === provider.toLowerCase() || t.configName === provider.toLowerCase(), ); - if (match) { - checksToRun = [match]; - } else { - // Unknown provider -- check if it has a config entry with an apiKey - checksToRun = [ - { - name: provider, - test: async () => { - const key = getConfigApiKey(provider); - if (key) return { pass: true, reason: 'API key found in config' }; - return { pass: false, reason: 'No API key in environment or config' }; - }, - }, - ]; + targets = match ? [match] : [{ name: provider, configName: provider.toLowerCase() }]; + } + + const results: Array<{ name: string; pass: boolean; reason: string }> = []; + + // Test API-key-based providers with real connectivity checks + for (const target of targets) { + const apiKey = resolveApiKey(target.configName, configuredProviders); + if (!apiKey) { + results.push({ name: target.name, pass: false, reason: 'Not configured (no API key found)' }); + continue; + } + output.writeln(output.dim(` Testing ${target.name}...`)); + const result = await testProviderConnectivity(target.name, apiKey); + results.push({ name: target.name, pass: result.ok, reason: result.reason }); + } + + // Test Ollama separately (endpoint-based, no API key needed) + if (testAll || !provider || provider.toLowerCase() === 'ollama') { + const baseUrl = (ollamaEntry?.baseUrl as string) || 'http://localhost:11434'; + output.writeln(output.dim(` Testing Ollama at ${baseUrl}...`)); + try { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 5000); + const res = await fetch(baseUrl, { signal: controller.signal }); + clearTimeout(timeout); + if (res.ok) { + results.push({ name: 'Ollama', pass: true, reason: `Connected at ${baseUrl}` }); + } else { + results.push({ name: 'Ollama', pass: false, reason: `HTTP ${res.status} from ${baseUrl}` }); + } + } catch { + results.push({ name: 'Ollama', pass: false, reason: `Unreachable at ${baseUrl}` }); + } + } + + // Also test any custom providers from config that were not in the known list + if (testAll || !provider) { + for (const cp of configuredProviders) { + const cpName = (cp.name as string) || ''; + const alreadyTested = results.some( + (r) => r.name.toLowerCase() === cpName.toLowerCase(), + ); + if (alreadyTested || !cpName) continue; + const apiKey = resolveApiKey(cpName, configuredProviders); + if (!apiKey) { + results.push({ name: cpName, pass: false, reason: 'No API key found' }); + } else { + // For custom providers we can only verify the key exists + results.push({ name: cpName, pass: true, reason: 'API key found (no test endpoint available)' }); + } } } let anyPassed = false; - const results: Array<{ name: string; pass: boolean; reason: string }> = []; - - for (const check of checksToRun) { - const result = await check.test(); - results.push({ name: check.name, ...result }); - if (result.pass) anyPassed = true; - } - output.writeln(); for (const r of results) { const icon = r.pass ? output.success('PASS') : output.error('FAIL'); output.writeln(` ${icon} ${r.name}: ${r.reason}`); + if (r.pass) anyPassed = true; } output.writeln(); - if (anyPassed) { + if (results.length === 0) { + output.writeln(output.warning('No providers to test. Use "providers configure" to add providers.')); + } else if (anyPassed) { output.writeln(output.success(`${results.filter((r) => r.pass).length}/${results.length} provider(s) passed.`)); } else { output.writeln(output.warning('No providers passed connectivity checks.')); diff --git a/v3/@claude-flow/cli/src/commands/security.ts b/v3/@claude-flow/cli/src/commands/security.ts index 18f1669f80..cf9fabc9f1 100644 --- a/v3/@claude-flow/cli/src/commands/security.ts +++ b/v3/@claude-flow/cli/src/commands/security.ts @@ -58,9 +58,9 @@ const scanCommand: Command = { maxBuffer: 10 * 1024 * 1024, stdio: ['pipe', 'pipe', 'pipe'], }); - } catch (auditErr: any) { + } catch (auditErr: unknown) { // npm audit exits non-zero when vulnerabilities found β€” stdout still has JSON - auditResult = auditErr.stdout || '{}'; + auditResult = (auditErr instanceof Error && 'stdout' in auditErr ? (auditErr as { stdout: string }).stdout : undefined) || '{}'; } try { diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts index 4420b1bdee..01cb00642c 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts @@ -8,7 +8,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { type MCPTool, getProjectCwd } from './types.js'; -import { validateIdentifier, validateAgentSpawn } from './validate-input.js'; +import { validateIdentifier, validateText, validateAgentSpawn } from './validate-input.js'; // Storage paths const STORAGE_DIR = '.claude-flow'; @@ -278,6 +278,9 @@ export const agentTools: MCPTool[] = [ required: ['agentId'], }, handler: async (input) => { + const v = validateIdentifier(input.agentId, 'agentId'); + if (!v.valid) return { success: false, error: `Input validation failed: ${v.error}` }; + const store = loadAgentStore(); const agentId = input.agentId as string; @@ -311,6 +314,9 @@ export const agentTools: MCPTool[] = [ required: ['agentId'], }, handler: async (input) => { + const v = validateIdentifier(input.agentId, 'agentId'); + if (!v.valid) return { agentId: input.agentId, status: 'not_found', error: `Input validation failed: ${v.error}` }; + const store = loadAgentStore(); const agentId = input.agentId as string; const agent = store.agents[agentId]; @@ -348,6 +354,15 @@ export const agentTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.status) { + const v = validateIdentifier(input.status, 'status'); + if (!v.valid) return { agents: [], total: 0, error: `Input validation failed: ${v.error}` }; + } + if (input.domain) { + const v = validateIdentifier(input.domain, 'domain'); + if (!v.valid) return { agents: [], total: 0, error: `Input validation failed: ${v.error}` }; + } + const store = loadAgentStore(); let agents = Object.values(store.agents); @@ -396,6 +411,11 @@ export const agentTools: MCPTool[] = [ required: ['action'], }, handler: async (input) => { + if (input.agentType) { + const v = validateIdentifier(input.agentType, 'agentType'); + if (!v.valid) return { action: input.action, error: `Input validation failed: ${v.error}` }; + } + const store = loadAgentStore(); const agents = Object.values(store.agents).filter(a => a.status !== 'terminated'); const action = (input.action as string) || 'status'; // Default to status @@ -511,6 +531,11 @@ export const agentTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.agentId) { + const v = validateIdentifier(input.agentId, 'agentId'); + if (!v.valid) return { agentId: input.agentId, error: `Input validation failed: ${v.error}` }; + } + const store = loadAgentStore(); const agents = Object.values(store.agents).filter(a => a.status !== 'terminated'); const threshold = (input.threshold as number) || 0.5; @@ -588,6 +613,13 @@ export const agentTools: MCPTool[] = [ required: ['agentId'], }, handler: async (input) => { + const v = validateIdentifier(input.agentId, 'agentId'); + if (!v.valid) return { success: false, agentId: input.agentId, error: `Input validation failed: ${v.error}` }; + if (input.status) { + const vs = validateIdentifier(input.status, 'status'); + if (!vs.valid) return { success: false, agentId: input.agentId, error: `Input validation failed: ${vs.error}` }; + } + const store = loadAgentStore(); const agentId = input.agentId as string; const agent = store.agents[agentId]; diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts index d419ca5003..f4dd29e600 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts @@ -12,6 +12,7 @@ */ import type { MCPTool } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; // ===== Shared validation helpers ===== @@ -116,6 +117,9 @@ export const agentdbPatternStore: MCPTool = { }, handler: async (params: Record) => { try { + const vPattern = validateText(params.pattern, 'pattern', 100_000); + if (!vPattern.valid) return { success: false, error: vPattern.error }; + if (params.type) { const vType = validateIdentifier(params.type, 'type'); if (!vType.valid) return { success: false, error: vType.error }; } const pattern = validateString(params.pattern, 'pattern'); if (!pattern) return { success: false, error: 'pattern is required (non-empty string, max 100KB)' }; const bridge = await getBridge(); @@ -147,6 +151,8 @@ export const agentdbPatternSearch: MCPTool = { }, handler: async (params: Record) => { try { + const vQuery = validateText(params.query, 'query', 10_000); + if (!vQuery.valid) return { results: [], error: vQuery.error }; const query = validateString(params.query, 'query', 10_000); if (!query) return { results: [], error: 'query is required (non-empty string, max 10KB)' }; const bridge = await getBridge(); @@ -179,6 +185,9 @@ export const agentdbFeedback: MCPTool = { }, handler: async (params: Record) => { try { + const vTaskId = validateIdentifier(params.taskId, 'taskId'); + if (!vTaskId.valid) return { success: false, error: vTaskId.error }; + if (params.agent) { const vAgent = validateIdentifier(params.agent, 'agent'); if (!vAgent.valid) return { success: false, error: vAgent.error }; } const taskId = validateString(params.taskId, 'taskId', 500); if (!taskId) return { success: false, error: 'taskId is required (non-empty string, max 500 chars)' }; const bridge = await getBridge(); @@ -212,6 +221,12 @@ export const agentdbCausalEdge: MCPTool = { }, handler: async (params: Record) => { try { + const vSourceId = validateIdentifier(params.sourceId, 'sourceId'); + if (!vSourceId.valid) return { success: false, error: vSourceId.error }; + const vTargetId = validateIdentifier(params.targetId, 'targetId'); + if (!vTargetId.valid) return { success: false, error: vTargetId.error }; + const vRelation = validateIdentifier(params.relation, 'relation'); + if (!vRelation.valid) return { success: false, error: vRelation.error }; const sourceId = validateString(params.sourceId, 'sourceId', 500); const targetId = validateString(params.targetId, 'targetId', 500); const relation = validateString(params.relation, 'relation', 200); @@ -247,6 +262,9 @@ export const agentdbRoute: MCPTool = { }, handler: async (params: Record) => { try { + const vTask = validateText(params.task, 'task', 10_000); + if (!vTask.valid) return { route: 'general', confidence: 0.5, agents: ['coder'], controller: 'error', error: vTask.error }; + if (params.context) { const vCtx = validateText(params.context, 'context', 10_000); if (!vCtx.valid) return { route: 'general', confidence: 0.5, agents: ['coder'], controller: 'error', error: vCtx.error }; } const task = validateString(params.task, 'task', 10_000); if (!task) return { route: 'general', confidence: 0.5, agents: ['coder'], controller: 'error', error: 'task is required (non-empty string)' }; const bridge = await getBridge(); @@ -276,6 +294,9 @@ export const agentdbSessionStart: MCPTool = { }, handler: async (params: Record) => { try { + const vSessionId = validateIdentifier(params.sessionId, 'sessionId'); + if (!vSessionId.valid) return { success: false, error: vSessionId.error }; + if (params.context) { const vCtx = validateText(params.context, 'context', 10_000); if (!vCtx.valid) return { success: false, error: vCtx.error }; } const sessionId = validateString(params.sessionId, 'sessionId', 500); if (!sessionId) return { success: false, error: 'sessionId is required (non-empty string)' }; const bridge = await getBridge(); @@ -306,6 +327,9 @@ export const agentdbSessionEnd: MCPTool = { }, handler: async (params: Record) => { try { + const vSessionId = validateIdentifier(params.sessionId, 'sessionId'); + if (!vSessionId.valid) return { success: false, error: vSessionId.error }; + if (params.summary) { const vSummary = validateText(params.summary, 'summary', 50_000); if (!vSummary.valid) return { success: false, error: vSummary.error }; } const sessionId = validateString(params.sessionId, 'sessionId', 500); if (!sessionId) return { success: false, error: 'sessionId is required (non-empty string)' }; const bridge = await getBridge(); @@ -342,6 +366,11 @@ export const agentdbHierarchicalStore: MCPTool = { }, handler: async (params: Record) => { try { + const vKey = validateIdentifier(params.key, 'key'); + if (!vKey.valid) return { success: false, error: vKey.error }; + const vValue = validateText(params.value, 'value'); + if (!vValue.valid) return { success: false, error: vValue.error }; + if (params.tier) { const vTier = validateIdentifier(params.tier, 'tier'); if (!vTier.valid) return { success: false, error: vTier.error }; } const key = validateString(params.key, 'key', 1000); const value = validateString(params.value, 'value'); if (!key) return { success: false, error: 'key is required (non-empty string, max 1KB)' }; @@ -375,6 +404,9 @@ export const agentdbHierarchicalRecall: MCPTool = { }, handler: async (params: Record) => { try { + const vQuery = validateText(params.query, 'query', 10_000); + if (!vQuery.valid) return { results: [], error: vQuery.error }; + if (params.tier) { const vTier = validateIdentifier(params.tier, 'tier'); if (!vTier.valid) return { results: [], error: vTier.error }; } const query = validateString(params.query, 'query', 10_000); if (!query) return { results: [], error: 'query is required (non-empty string, max 10KB)' }; const tier = validateString(params.tier, 'tier', 20); @@ -450,6 +482,8 @@ export const agentdbBatch: MCPTool = { }, handler: async (params: Record) => { try { + const vOp = validateIdentifier(params.operation, 'operation'); + if (!vOp.valid) return { success: false, error: vOp.error }; const operation = validateString(params.operation, 'operation', 20); if (!operation) return { success: false, error: 'operation is required (string)' }; if (!['insert', 'update', 'delete'].includes(operation)) { @@ -500,6 +534,8 @@ export const agentdbContextSynthesize: MCPTool = { }, handler: async (params: Record) => { try { + const vQuery = validateText(params.query, 'query', 10_000); + if (!vQuery.valid) return { success: false, error: vQuery.error }; const query = validateString(params.query, 'query', 10_000); if (!query) return { success: false, error: 'query is required (non-empty string, max 10KB)' }; const bridge = await getBridge(); @@ -528,6 +564,8 @@ export const agentdbSemanticRoute: MCPTool = { }, handler: async (params: Record) => { try { + const vInput = validateText(params.input, 'input', 10_000); + if (!vInput.valid) return { route: null, error: vInput.error }; const input = validateString(params.input, 'input', 10_000); if (!input) return { route: null, error: 'input is required (non-empty string, max 10KB)' }; const bridge = await getBridge(); diff --git a/v3/@claude-flow/cli/src/mcp-tools/analyze-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/analyze-tools.ts index 144a94d7ff..0e1cb46798 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/analyze-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/analyze-tools.ts @@ -4,6 +4,7 @@ */ import type { MCPTool } from './types.js'; +import { validateIdentifier, validatePath } from './validate-input.js'; import { analyzeDiff, assessFileRisk, @@ -50,6 +51,7 @@ export const analyzeDiffTool: MCPTool = { }, }, handler: async (params: Record) => { + if (params.ref) { const vRef = validateIdentifier(params.ref, 'ref'); if (!vRef.valid) return { error: true, message: vRef.error, ref: params.ref }; } const ref = (params.ref as string) || 'HEAD'; const includeFileRisks = params.includeFileRisks !== false; const includeReviewers = params.includeReviewers !== false; @@ -110,6 +112,7 @@ export const diffRiskTool: MCPTool = { }, }, handler: async (params: Record) => { + if (params.ref) { const vRef = validateIdentifier(params.ref, 'ref'); if (!vRef.valid) return { error: true, message: vRef.error, ref: params.ref }; } const ref = (params.ref as string) || 'HEAD'; try { @@ -152,6 +155,7 @@ export const diffClassifyTool: MCPTool = { }, }, handler: async (params: Record) => { + if (params.ref) { const vRef = validateIdentifier(params.ref, 'ref'); if (!vRef.valid) return { error: true, message: vRef.error, ref: params.ref }; } const ref = (params.ref as string) || 'HEAD'; try { @@ -198,6 +202,7 @@ export const diffReviewersTool: MCPTool = { }, }, handler: async (params: Record) => { + if (params.ref) { const vRef = validateIdentifier(params.ref, 'ref'); if (!vRef.valid) return { error: true, message: vRef.error, ref: params.ref }; } const ref = (params.ref as string) || 'HEAD'; const limit = (params.limit as number) || 5; @@ -256,6 +261,8 @@ export const fileRiskTool: MCPTool = { required: ['path'], }, handler: async (params: Record) => { + const vPath = validatePath(params.path, 'path'); + if (!vPath.valid) return { file: params.path, risk: 'unknown', score: 0, reasons: [vPath.error] }; const file: DiffFile = { path: params.path as string, status: (params.status as DiffFile['status']) || 'modified', @@ -296,6 +303,7 @@ export const diffStatsTool: MCPTool = { }, }, handler: async (params: Record) => { + if (params.ref) { const vRef = validateIdentifier(params.ref, 'ref'); if (!vRef.valid) return { error: true, message: vRef.error, ref: params.ref }; } const ref = (params.ref as string) || 'HEAD'; try { diff --git a/v3/@claude-flow/cli/src/mcp-tools/autopilot-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/autopilot-tools.ts index 65ceb6a4ba..0b8afbed1d 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/autopilot-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/autopilot-tools.ts @@ -9,6 +9,7 @@ */ import type { MCPTool } from './types.js'; +import { validateText } from './validate-input.js'; import { loadState, saveState, appendLog, loadLog, discoverTasks, isTerminal, tryLoadLearning, @@ -194,6 +195,8 @@ const autopilotHistory: MCPTool = { required: ['query'], }, handler: async (params: Record) => { + const vQuery = validateText(params.query, 'query'); + if (!vQuery.valid) return ok({ query: '', results: [], error: vQuery.error }); const query = String(params.query || ''); const limit = validateNumber(params.limit, 1, 100, 10); const learning = await tryLoadLearning(); diff --git a/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts index 3ef8774994..42a76e2c8a 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts @@ -6,6 +6,7 @@ */ import type { MCPTool, MCPToolResult } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; // Session registry for multi-session support const browserSessions = new Map { + const vUrl = validateText(input.url, 'url'); + if (!vUrl.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vUrl.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { url, session, waitUntil } = input as { url: string; session?: string; @@ -193,6 +197,8 @@ export const browserTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.selector) { const vSel = validateText(input.selector, 'selector'); if (!vSel.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vSel.error }) }], isError: true }; } + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { session, interactive, compact, depth, selector } = input as { session?: string; interactive?: boolean; @@ -222,6 +228,8 @@ export const browserTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.path) { const vP = validateText(input.path, 'path'); if (!vP.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vP.error }) }], isError: true }; } + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { session, path, fullPage } = input as { session?: string; path?: string; @@ -253,6 +261,9 @@ export const browserTools: MCPTool[] = [ required: ['target'], }, handler: async (input) => { + const vTarget = validateText(input.target, 'target'); + if (!vTarget.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vTarget.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { target, session, button, count } = input as { target: string; session?: string; @@ -280,6 +291,11 @@ export const browserTools: MCPTool[] = [ required: ['target', 'value'], }, handler: async (input) => { + const vTarget = validateText(input.target, 'target'); + if (!vTarget.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vTarget.error }) }], isError: true }; + const vValue = validateText(input.value, 'value'); + if (!vValue.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vValue.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { target, value, session } = input as { target: string; value: string; @@ -304,6 +320,11 @@ export const browserTools: MCPTool[] = [ required: ['target', 'text'], }, handler: async (input) => { + const vTarget = validateText(input.target, 'target'); + if (!vTarget.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vTarget.error }) }], isError: true }; + const vText = validateText(input.text, 'text'); + if (!vText.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vText.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { target, text, session, delay } = input as { target: string; text: string; @@ -329,6 +350,9 @@ export const browserTools: MCPTool[] = [ required: ['key'], }, handler: async (input) => { + const vKey = validateText(input.key, 'key'); + if (!vKey.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vKey.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { key, session } = input as { key: string; session?: string }; return execBrowserCommand(['press', key], session); }, @@ -347,6 +371,9 @@ export const browserTools: MCPTool[] = [ required: ['target'], }, handler: async (input) => { + const vTarget = validateText(input.target, 'target'); + if (!vTarget.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vTarget.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { target, session } = input as { target: string; session?: string }; return execBrowserCommand(['hover', target], session); }, @@ -366,6 +393,11 @@ export const browserTools: MCPTool[] = [ required: ['target', 'value'], }, handler: async (input) => { + const vTarget = validateText(input.target, 'target'); + if (!vTarget.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vTarget.error }) }], isError: true }; + const vValue = validateText(input.value, 'value'); + if (!vValue.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vValue.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { target, value, session } = input as { target: string; value: string; @@ -388,6 +420,9 @@ export const browserTools: MCPTool[] = [ required: ['target'], }, handler: async (input) => { + const vTarget = validateText(input.target, 'target'); + if (!vTarget.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vTarget.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { target, session } = input as { target: string; session?: string }; return execBrowserCommand(['check', target], session); }, @@ -406,6 +441,9 @@ export const browserTools: MCPTool[] = [ required: ['target'], }, handler: async (input) => { + const vTarget = validateText(input.target, 'target'); + if (!vTarget.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vTarget.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { target, session } = input as { target: string; session?: string }; return execBrowserCommand(['uncheck', target], session); }, @@ -453,6 +491,9 @@ export const browserTools: MCPTool[] = [ required: ['target'], }, handler: async (input) => { + const vTarget = validateText(input.target, 'target'); + if (!vTarget.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vTarget.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { target, session } = input as { target: string; session?: string }; return execBrowserCommand(['get', 'text', target], session); }, @@ -471,6 +512,9 @@ export const browserTools: MCPTool[] = [ required: ['target'], }, handler: async (input) => { + const vTarget = validateText(input.target, 'target'); + if (!vTarget.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vTarget.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { target, session } = input as { target: string; session?: string }; return execBrowserCommand(['get', 'value', target], session); }, @@ -527,6 +571,10 @@ export const browserTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.selector) { const vSel = validateText(input.selector, 'selector'); if (!vSel.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vSel.error }) }], isError: true }; } + if (input.text) { const vT = validateText(input.text, 'text'); if (!vT.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vT.error }) }], isError: true }; } + if (input.url) { const vU = validateText(input.url, 'url'); if (!vU.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vU.error }) }], isError: true }; } + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { selector, text, url, timeout, session } = input as { selector?: string; text?: string; @@ -560,6 +608,9 @@ export const browserTools: MCPTool[] = [ required: ['script'], }, handler: async (input) => { + const vScript = validateText(input.script, 'script'); + if (!vScript.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vScript.error }) }], isError: true }; + if (input.session) { const vS = validateIdentifier(input.session, 'session'); if (!vS.valid) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vS.error }) }], isError: true }; } const { script, session } = input as { script: string; session?: string }; return execBrowserCommand(['eval', script], session); }, diff --git a/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts index ca8a29ade2..0bece7ab2a 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/claims-tools.ts @@ -8,6 +8,7 @@ */ import type { MCPTool } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; // Inline claim service since we can't import external modules interface Claimant { @@ -120,6 +121,10 @@ export const claimsTools: MCPTool[] = [ const claimantStr = input.claimant as string; const context = input.context as string | undefined; + { const v = validateIdentifier(issueId, 'issueId'); if (!v.valid) return { success: false, error: v.error }; } + { const v = validateText(claimantStr, 'claimant'); if (!v.valid) return { success: false, error: v.error }; } + if (context) { const v = validateText(context, 'context'); if (!v.valid) return { success: false, error: v.error }; } + const claimant = parseClaimant(claimantStr); if (!claimant) { return { success: false, error: 'Invalid claimant format. Use "human:userId:name" or "agent:agentId:agentType"' }; @@ -186,6 +191,10 @@ export const claimsTools: MCPTool[] = [ const claimantStr = input.claimant as string; const reason = input.reason as string | undefined; + { const v = validateIdentifier(issueId, 'issueId'); if (!v.valid) return { success: false, error: v.error }; } + { const v = validateText(claimantStr, 'claimant'); if (!v.valid) return { success: false, error: v.error }; } + if (reason) { const v = validateText(reason, 'reason'); if (!v.valid) return { success: false, error: v.error }; } + const claimant = parseClaimant(claimantStr); if (!claimant) { return { success: false, error: 'Invalid claimant format' }; @@ -253,6 +262,11 @@ export const claimsTools: MCPTool[] = [ const reason = input.reason as string | undefined; const progress = (input.progress as number) || 0; + { const v = validateIdentifier(issueId, 'issueId'); if (!v.valid) return { success: false, error: v.error }; } + { const v = validateText(fromStr, 'from'); if (!v.valid) return { success: false, error: v.error }; } + { const v = validateText(toStr, 'to'); if (!v.valid) return { success: false, error: v.error }; } + if (reason) { const v = validateText(reason, 'reason'); if (!v.valid) return { success: false, error: v.error }; } + const from = parseClaimant(fromStr); const to = parseClaimant(toStr); @@ -311,6 +325,9 @@ export const claimsTools: MCPTool[] = [ const issueId = input.issueId as string; const claimantStr = input.claimant as string; + { const v = validateIdentifier(issueId, 'issueId'); if (!v.valid) return { success: false, error: v.error }; } + { const v = validateText(claimantStr, 'claimant'); if (!v.valid) return { success: false, error: v.error }; } + const claimant = parseClaimant(claimantStr); if (!claimant) { return { success: false, error: 'Invalid claimant format' }; @@ -385,6 +402,9 @@ export const claimsTools: MCPTool[] = [ const note = input.note as string | undefined; const progress = input.progress as number | undefined; + { const v = validateIdentifier(issueId, 'issueId'); if (!v.valid) return { success: false, error: v.error }; } + if (note) { const v = validateText(note, 'note'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadClaims(); const claim = store.claims[issueId]; @@ -440,6 +460,9 @@ export const claimsTools: MCPTool[] = [ const claimantFilter = input.claimant as string | undefined; const agentType = input.agentType as string | undefined; + if (claimantFilter) { const v = validateText(claimantFilter, 'claimant'); if (!v.valid) return { success: false, error: v.error }; } + if (agentType) { const v = validateIdentifier(agentType, 'agentType'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadClaims(); let claims = Object.values(store.claims); @@ -500,6 +523,9 @@ export const claimsTools: MCPTool[] = [ const preferredTypes = input.preferredTypes as string[] | undefined; const context = input.context as string | undefined; + { const v = validateIdentifier(issueId, 'issueId'); if (!v.valid) return { success: false, error: v.error }; } + if (context) { const v = validateText(context, 'context'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadClaims(); const claim = store.claims[issueId]; @@ -553,6 +579,9 @@ export const claimsTools: MCPTool[] = [ const issueId = input.issueId as string; const stealerStr = input.stealer as string; + { const v = validateIdentifier(issueId, 'issueId'); if (!v.valid) return { success: false, error: v.error }; } + { const v = validateText(stealerStr, 'stealer'); if (!v.valid) return { success: false, error: v.error }; } + const stealer = parseClaimant(stealerStr); if (!stealer) { return { success: false, error: 'Invalid claimant format' }; @@ -618,6 +647,8 @@ export const claimsTools: MCPTool[] = [ handler: async (input) => { const agentType = input.agentType as string | undefined; + if (agentType) { const v = validateIdentifier(agentType, 'agentType'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadClaims(); let stealableIssues = Object.entries(store.stealable).map(([issueId, info]) => ({ issueId, @@ -660,6 +691,9 @@ export const claimsTools: MCPTool[] = [ const agentId = input.agentId as string | undefined; const agentType = input.agentType as string | undefined; + if (agentId) { const v = validateIdentifier(agentId, 'agentId'); if (!v.valid) return { success: false, error: v.error }; } + if (agentType) { const v = validateIdentifier(agentType, 'agentType'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadClaims(); const claims = Object.values(store.claims); diff --git a/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts index 411c2028ea..83cb19ae84 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/config-tools.ts @@ -7,6 +7,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; // Storage paths const STORAGE_DIR = '.claude-flow'; @@ -133,6 +134,14 @@ export const configTools: MCPTool[] = [ required: ['key'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vKey = validateText(input.key, 'key', 256); + if (!vKey.valid) return { success: false, error: vKey.error }; + if (input.scope) { + const v = validateIdentifier(input.scope, 'scope'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadConfigStore(); const key = input.key as string; const scope = (input.scope as string) || 'default'; @@ -173,6 +182,14 @@ export const configTools: MCPTool[] = [ required: ['key', 'value'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vKey = validateText(input.key, 'key', 256); + if (!vKey.valid) return { success: false, error: vKey.error }; + if (input.scope) { + const v = validateIdentifier(input.scope, 'scope'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadConfigStore(); const key = input.key as string; const value = input.value; @@ -214,6 +231,16 @@ export const configTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.scope) { + const v = validateIdentifier(input.scope, 'scope'); + if (!v.valid) return { success: false, error: v.error }; + } + if (input.prefix) { + const v = validateText(input.prefix, 'prefix', 256); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadConfigStore(); const scope = (input.scope as string) || 'default'; const prefix = input.prefix as string; @@ -267,6 +294,16 @@ export const configTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.scope) { + const v = validateIdentifier(input.scope, 'scope'); + if (!v.valid) return { success: false, error: v.error }; + } + if (input.key) { + const v = validateText(input.key, 'key', 256); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadConfigStore(); const scope = (input.scope as string) || 'default'; const key = input.key as string; @@ -318,6 +355,12 @@ export const configTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.scope) { + const v = validateIdentifier(input.scope, 'scope'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadConfigStore(); const scope = (input.scope as string) || 'default'; const includeDefaults = input.includeDefaults !== false; @@ -357,6 +400,12 @@ export const configTools: MCPTool[] = [ required: ['config'], }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.scope) { + const v = validateIdentifier(input.scope, 'scope'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadConfigStore(); const config = filterDangerousKeys(input.config as Record); const scope = (input.scope as string) || 'default'; diff --git a/v3/@claude-flow/cli/src/mcp-tools/coordination-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/coordination-tools.ts index 20f8ec3a9c..e07a94e466 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/coordination-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/coordination-tools.ts @@ -10,6 +10,7 @@ */ import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; @@ -214,6 +215,7 @@ export const coordinationTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.task) { const vTask = validateText(input.task, 'task'); if (!vTask.valid) return { success: false, error: vTask.error }; } const store = loadCoordStore(); const action = (input.action as string) || 'get'; @@ -372,6 +374,7 @@ export const coordinationTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.nodeId) { const vNode = validateIdentifier(input.nodeId, 'nodeId'); if (!vNode.valid) return { success: false, error: vNode.error }; } const store = loadCoordStore(); const action = (input.action as string) || 'list'; @@ -467,6 +470,8 @@ export const coordinationTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.proposalId) { const vProp = validateIdentifier(input.proposalId, 'proposalId'); if (!vProp.valid) return { success: false, error: vProp.error }; } + if (input.voterId) { const vVoter = validateIdentifier(input.voterId, 'voterId'); if (!vVoter.valid) return { success: false, error: vVoter.error }; } const store = loadCoordStore(); const action = (input.action as string) || 'status'; const strategy = (input.strategy as string) || 'raft'; @@ -707,6 +712,11 @@ export const coordinationTools: MCPTool[] = [ required: ['task'], }, handler: async (input) => { + const vTask = validateText(input.task, 'task'); + if (!vTask.valid) return { success: false, error: vTask.error }; + if (input.agents && Array.isArray(input.agents)) { + for (const a of input.agents as string[]) { const vA = validateIdentifier(a, 'agents[]'); if (!vA.valid) return { success: false, error: vA.error }; } + } const store = loadCoordStore(); const task = input.task as string; const agents = (input.agents as string[]) || Object.keys(store.nodes); diff --git a/v3/@claude-flow/cli/src/mcp-tools/daa-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/daa-tools.ts index 68e01d1f26..6fea144b0b 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/daa-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/daa-tools.ts @@ -10,6 +10,7 @@ */ import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; @@ -103,6 +104,10 @@ export const daaTools: MCPTool[] = [ required: ['id'], }, handler: async (input) => { + const vId = validateIdentifier(input.id, 'id'); + if (!vId.valid) return { success: false, error: vId.error }; + if (input.name) { const vName = validateText(input.name, 'name'); if (!vName.valid) return { success: false, error: vName.error }; } + if (input.type) { const vType = validateIdentifier(input.type, 'type'); if (!vType.valid) return { success: false, error: vType.error }; } const store = loadDAAStore(); const id = input.id as string; @@ -167,6 +172,9 @@ export const daaTools: MCPTool[] = [ required: ['agentId'], }, handler: async (input) => { + const vAgentId = validateIdentifier(input.agentId, 'agentId'); + if (!vAgentId.valid) return { success: false, error: vAgentId.error }; + if (input.feedback) { const vFeedback = validateText(input.feedback, 'feedback'); if (!vFeedback.valid) return { success: false, error: vFeedback.error }; } const store = loadDAAStore(); const agentId = input.agentId as string; const agent = store.agents[agentId]; @@ -227,6 +235,10 @@ export const daaTools: MCPTool[] = [ required: ['id', 'name'], }, handler: async (input) => { + const vId = validateIdentifier(input.id, 'id'); + if (!vId.valid) return { success: false, error: vId.error }; + const vName = validateText(input.name, 'name'); + if (!vName.valid) return { success: false, error: vName.error }; const store = loadDAAStore(); const id = input.id as string; @@ -269,6 +281,8 @@ export const daaTools: MCPTool[] = [ required: ['workflowId'], }, handler: async (input) => { + const vWorkflowId = validateIdentifier(input.workflowId, 'workflowId'); + if (!vWorkflowId.valid) return { success: false, error: vWorkflowId.error }; const store = loadDAAStore(); const workflowId = input.workflowId as string; const workflow = store.workflows[workflowId]; @@ -319,6 +333,12 @@ export const daaTools: MCPTool[] = [ required: ['sourceAgentId', 'targetAgentIds'], }, handler: async (input) => { + const vSourceId = validateIdentifier(input.sourceAgentId, 'sourceAgentId'); + if (!vSourceId.valid) return { success: false, error: vSourceId.error }; + if (input.targetAgentIds && Array.isArray(input.targetAgentIds)) { + for (const t of input.targetAgentIds as string[]) { const vT = validateIdentifier(t, 'targetAgentIds[]'); if (!vT.valid) return { success: false, error: vT.error }; } + } + if (input.knowledgeDomain) { const vDomain = validateIdentifier(input.knowledgeDomain, 'knowledgeDomain'); if (!vDomain.valid) return { success: false, error: vDomain.error }; } const store = loadDAAStore(); const sourceId = input.sourceAgentId as string; const targetIds = input.targetAgentIds as string[]; @@ -376,6 +396,7 @@ export const daaTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.agentId) { const vAgentId = validateIdentifier(input.agentId, 'agentId'); if (!vAgentId.valid) return { success: false, error: vAgentId.error }; } const store = loadDAAStore(); const agentId = input.agentId as string; @@ -432,6 +453,8 @@ export const daaTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.agentId) { const vAgentId = validateIdentifier(input.agentId, 'agentId'); if (!vAgentId.valid) return { success: false, error: vAgentId.error }; } + if (input.pattern) { const vPattern = validateIdentifier(input.pattern, 'pattern'); if (!vPattern.valid) return { success: false, error: vPattern.error }; } const store = loadDAAStore(); const agentId = input.agentId as string; const action = (input.action as string) || 'analyze'; diff --git a/v3/@claude-flow/cli/src/mcp-tools/embeddings-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/embeddings-tools.ts index 8adde5d1ba..0dbbaed2d0 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/embeddings-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/embeddings-tools.ts @@ -8,6 +8,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs'; import { join, resolve } from 'path'; import type { MCPTool } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; // Configuration paths const CONFIG_DIR = '.claude-flow'; @@ -289,6 +290,9 @@ export const embeddingsTools: MCPTool[] = [ } const text = input.text as string; + + { const v = validateText(text, 'text'); if (!v.valid) return { success: false, error: v.error }; } + const useHyperbolic = input.hyperbolic === true && config.hyperbolic.enabled; // Generate real ONNX embedding @@ -357,6 +361,9 @@ export const embeddingsTools: MCPTool[] = [ const text2 = input.text2 as string; const metric = (input.metric as string) || 'cosine'; + { const v = validateText(text1, 'text1'); if (!v.valid) return { success: false, error: v.error }; } + { const v = validateText(text2, 'text2'); if (!v.valid) return { success: false, error: v.error }; } + // Generate real ONNX embeddings for both texts const [emb1, emb2] = await Promise.all([ generateRealEmbedding(text1, config.dimension), @@ -449,6 +456,9 @@ export const embeddingsTools: MCPTool[] = [ const threshold = (input.threshold as number) || 0.5; const namespace = input.namespace as string; + { const v = validateText(query, 'query'); if (!v.valid) return { success: false, error: v.error }; } + if (namespace) { const v = validateIdentifier(namespace, 'namespace'); if (!v.valid) return { success: false, error: v.error }; } + const startTime = performance.now(); // Generate real ONNX embedding for query diff --git a/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts index f2a5906385..5b4eb437dc 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/github-tools.ts @@ -6,6 +6,7 @@ */ import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { execSync } from 'node:child_process'; @@ -97,6 +98,10 @@ export const githubTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.owner) { const v = validateIdentifier(input.owner as string, 'owner'); if (!v.valid) return { success: false, error: v.error }; } + if (input.repo) { const v = validateIdentifier(input.repo as string, 'repo'); if (!v.valid) return { success: false, error: v.error }; } + if (input.branch) { const v = validateIdentifier(input.branch as string, 'branch'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadGitHubStore(); const branch = (input.branch as string) || 'main'; const cwd = getProjectCwd(); @@ -181,6 +186,13 @@ export const githubTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.owner) { const v = validateIdentifier(input.owner as string, 'owner'); if (!v.valid) return { success: false, error: v.error }; } + if (input.repo) { const v = validateIdentifier(input.repo as string, 'repo'); if (!v.valid) return { success: false, error: v.error }; } + if (input.title) { const v = validateText(input.title as string, 'title'); if (!v.valid) return { success: false, error: v.error }; } + if (input.body) { const v = validateText(input.body as string, 'body'); if (!v.valid) return { success: false, error: v.error }; } + if (input.branch) { const v = validateIdentifier(input.branch as string, 'branch'); if (!v.valid) return { success: false, error: v.error }; } + if (input.baseBranch) { const v = validateIdentifier(input.baseBranch as string, 'baseBranch'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadGitHubStore(); const action = (input.action as string) || 'list'; const gh = hasGhCli(); @@ -279,6 +291,11 @@ export const githubTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.owner) { const v = validateIdentifier(input.owner as string, 'owner'); if (!v.valid) return { success: false, error: v.error }; } + if (input.repo) { const v = validateIdentifier(input.repo as string, 'repo'); if (!v.valid) return { success: false, error: v.error }; } + if (input.title) { const v = validateText(input.title as string, 'title'); if (!v.valid) return { success: false, error: v.error }; } + if (input.body) { const v = validateText(input.body as string, 'body'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadGitHubStore(); const action = (input.action as string) || 'list'; const gh = hasGhCli(); @@ -364,6 +381,11 @@ export const githubTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.owner) { const v = validateIdentifier(input.owner as string, 'owner'); if (!v.valid) return { success: false, error: v.error }; } + if (input.repo) { const v = validateIdentifier(input.repo as string, 'repo'); if (!v.valid) return { success: false, error: v.error }; } + if (input.workflowId) { const v = validateIdentifier(input.workflowId as string, 'workflowId'); if (!v.valid) return { success: false, error: v.error }; } + if (input.ref) { const v = validateIdentifier(input.ref as string, 'ref'); if (!v.valid) return { success: false, error: v.error }; } + const action = (input.action as string) || 'list'; const gh = hasGhCli(); @@ -437,6 +459,9 @@ export const githubTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.owner) { const v = validateIdentifier(input.owner as string, 'owner'); if (!v.valid) return { success: false, error: v.error }; } + if (input.repo) { const v = validateIdentifier(input.repo as string, 'repo'); if (!v.valid) return { success: false, error: v.error }; } + const metric = (input.metric as string) || 'all'; const timeRange = (input.timeRange as string) || '30d'; const cwd = getProjectCwd(); diff --git a/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts index 14d3d60b0d..3fb987f972 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/guidance-tools.ts @@ -8,6 +8,7 @@ */ import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; import { existsSync, readFileSync, readdirSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -378,6 +379,8 @@ const guidanceCapabilities: MCPTool = { const area = params.area as string | undefined; const format = (params.format as string) || 'summary'; + if (area) { const v = validateIdentifier(area, 'area'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }, null, 2) }], isError: true }; } + if (area) { const cap = CAPABILITY_CATALOG[area]; if (!cap) { @@ -420,6 +423,9 @@ const guidanceRecommend: MCPTool = { }, handler: async (params: Record) => { const task = params.task as string; + + { const v = validateText(task, 'task'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }, null, 2) }], isError: true }; } + const matches: Array<{ area: string; capability: CapabilityArea; workflow: string; score: number }> = []; for (const route of TASK_ROUTES) { @@ -538,6 +544,9 @@ const guidanceWorkflow: MCPTool = { }, handler: async (params: Record) => { const type = params.type as string; + + { const v = validateIdentifier(type, 'type'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }, null, 2) }], isError: true }; } + const template = WORKFLOW_TEMPLATES[type]; if (!template) { @@ -588,6 +597,8 @@ const guidanceQuickRef: MCPTool = { handler: async (params: Record) => { const domain = params.domain as string; + { const v = validateIdentifier(domain, 'domain'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }, null, 2) }], isError: true }; } + const refs: Record }> = { 'getting-started': { title: 'Getting Started', diff --git a/v3/@claude-flow/cli/src/mcp-tools/hive-mind-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hive-mind-tools.ts index 129586a550..94ee0a9a23 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/hive-mind-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/hive-mind-tools.ts @@ -7,6 +7,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; // Storage paths const STORAGE_DIR = '.claude-flow'; @@ -234,6 +235,9 @@ export const hiveMindTools: MCPTool[] = [ return { success: false, error: 'Hive-mind not initialized. Run hive-mind/init first.' }; } + if (input.agentType) { const v = validateIdentifier(input.agentType as string, 'agentType'); if (!v.valid) return { success: false, error: v.error }; } + if (input.prefix) { const v = validateIdentifier(input.prefix as string, 'prefix'); if (!v.valid) return { success: false, error: v.error }; } + const count = Math.min(Math.max(1, (input.count as number) || 1), 20); // Cap at 20 const role = (input.role as string) || 'worker'; const agentType = (input.agentType as string) || 'worker'; @@ -294,6 +298,8 @@ export const hiveMindTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.queenId) { const v = validateIdentifier(input.queenId as string, 'queenId'); if (!v.valid) return { success: false, error: v.error }; } + const state = loadHiveState(); const hiveId = `hive-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; const queenId = (input.queenId as string) || `queen-${Date.now()}`; @@ -444,6 +450,8 @@ export const hiveMindTools: MCPTool[] = [ const state = loadHiveState(); const agentId = input.agentId as string; + { const v = validateIdentifier(agentId, 'agentId'); if (!v.valid) return { success: false, error: v.error }; } + if (!state.initialized) { return { success: false, error: 'Hive-mind not initialized' }; } @@ -477,6 +485,8 @@ export const hiveMindTools: MCPTool[] = [ const state = loadHiveState(); const agentId = input.agentId as string; + { const v = validateIdentifier(agentId, 'agentId'); if (!v.valid) return { success: false, agentId, error: v.error }; } + const index = state.workers.indexOf(agentId); if (index > -1) { state.workers.splice(index, 1); @@ -513,6 +523,10 @@ export const hiveMindTools: MCPTool[] = [ required: ['action'], }, handler: async (input) => { + if (input.proposalId) { const v = validateIdentifier(input.proposalId as string, 'proposalId'); if (!v.valid) return { action: input.action, error: v.error }; } + if (input.voterId) { const v = validateIdentifier(input.voterId as string, 'voterId'); if (!v.valid) return { action: input.action, error: v.error }; } + if (input.type) { const v = validateText(input.type as string, 'type'); if (!v.valid) return { action: input.action, error: v.error }; } + const state = loadHiveState(); const action = input.action as string; const strategy = (input.strategy as ConsensusStrategy) || 'raft'; @@ -826,6 +840,9 @@ export const hiveMindTools: MCPTool[] = [ return { success: false, error: 'Hive-mind not initialized' }; } + { const v = validateText(input.message as string, 'message'); if (!v.valid) return { success: false, error: v.error }; } + if (input.fromId) { const v = validateIdentifier(input.fromId as string, 'fromId'); if (!v.valid) return { success: false, error: v.error }; } + const messageId = `msg-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; // Store in shared memory @@ -930,6 +947,8 @@ export const hiveMindTools: MCPTool[] = [ required: ['action'], }, handler: async (input) => { + if (input.key) { const v = validateIdentifier(input.key as string, 'key'); if (!v.valid) return { action: input.action, error: v.error }; } + const state = loadHiveState(); const action = input.action as string; const key = input.key as string; diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts index 337123f931..ef5e98bf69 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts @@ -6,6 +6,7 @@ import { mkdirSync, writeFileSync, existsSync, readFileSync, statSync, unlinkSync, readdirSync, rmSync } from 'fs'; import { dirname, join, resolve } from 'path'; import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validateText, validatePath } from './validate-input.js'; // Real vector search functions - lazy loaded to avoid circular imports let searchEntriesFn: ((options: { @@ -709,6 +710,8 @@ export const hooksPreEdit: MCPTool = { const filePath = params.filePath as string; const operation = (params.operation as string) || 'update'; + { const v = validatePath(filePath, 'filePath'); if (!v.valid) return { success: false, error: v.error }; } + const suggestedAgents = suggestAgentsForFile(filePath); const ext = getFileExtension(filePath); @@ -750,6 +753,9 @@ export const hooksPostEdit: MCPTool = { const success = params.success !== false; const agent = params.agent as string | undefined; + { const v = validatePath(filePath, 'filePath'); if (!v.valid) return { success: false, error: v.error }; } + if (agent) { const v = validateIdentifier(agent, 'agent'); if (!v.valid) return { success: false, error: v.error }; } + // Wire recordFeedback through bridge (issue #1209) let feedbackResult: { success: boolean; controller: string; updated: number } | null = null; try { @@ -791,6 +797,9 @@ export const hooksPreCommand: MCPTool = { }, handler: async (params: Record) => { const command = params.command as string; + + { const v = validateText(command, 'command'); if (!v.valid) return { success: false, error: v.error }; } + const assessment = assessCommandRisk(command); const riskLevel = assessment.level >= 0.8 ? 'critical' @@ -831,6 +840,8 @@ export const hooksPostCommand: MCPTool = { const exitCode = (params.exitCode as number) || 0; const success = exitCode === 0; + { const v = validateText(command, 'command'); if (!v.valid) return { success: false, error: v.error }; } + // Persist command outcome via AgentDB let _storedIn: 'agentdb' | 'json-store' | 'none' = 'none'; try { @@ -883,6 +894,9 @@ export const hooksRoute: MCPTool = { const context = params.context as string | undefined; const useSemanticRouter = params.useSemanticRouter !== false; + { const v = validateText(task, 'task'); if (!v.valid) return { success: false, error: v.error }; } + if (context) { const v = validateText(context, 'context'); if (!v.valid) return { success: false, error: v.error }; } + // Phase 5: Try AgentDB's SemanticRouter / LearningSystem first if (useSemanticRouter) { try { @@ -1164,6 +1178,11 @@ export const hooksPreTask: MCPTool = { const taskId = params.taskId as string; const description = params.description as string; const filePath = params.filePath as string | undefined; + + { const v = validateIdentifier(taskId, 'taskId'); if (!v.valid) return { success: false, error: v.error }; } + { const v = validateText(description, 'description'); if (!v.valid) return { success: false, error: v.error }; } + if (filePath) { const v = validatePath(filePath, 'filePath'); if (!v.valid) return { success: false, error: v.error }; } + const suggestion = suggestAgentsForTask(description); // Determine complexity @@ -1256,6 +1275,9 @@ export const hooksPostTask: MCPTool = { const quality = (params.quality as number) || (success ? 0.85 : 0.3); const startTime = Date.now(); + { const v = validateIdentifier(taskId, 'taskId'); if (!v.valid) return { success: false, error: v.error }; } + if (agent) { const v = validateIdentifier(agent, 'agent'); if (!v.valid) return { success: false, error: v.error }; } + // Phase 3: Wire recordFeedback through bridge β†’ LearningSystem + ReasoningBank let feedbackResult: { success: boolean; controller: string; updated: number } | null = null; try { @@ -1394,6 +1416,9 @@ export const hooksExplain: MCPTool = { }, handler: async (params: Record) => { const task = params.task as string; + + { const v = validateText(task, 'task'); if (!v.valid) return { success: false, error: v.error }; } + const suggestion = suggestAgentsForTask(task); const taskLower = task.toLowerCase(); @@ -1638,6 +1663,9 @@ export const hooksTransfer: MCPTool = { const minConfidence = (params.minConfidence as number) || 0.7; const filter = params.filter as string; + { const v = validatePath(sourcePath, 'sourcePath'); if (!v.valid) return { success: false, error: v.error }; } + if (filter) { const v = validateIdentifier(filter, 'filter'); if (!v.valid) return { success: false, error: v.error }; } + // Try to load patterns from source project's memory store const sourceMemoryPath = join(resolve(sourcePath), MEMORY_DIR, MEMORY_FILE); let sourceStore: MemoryStore = { entries: {}, version: '3.0.0' }; @@ -1716,6 +1744,8 @@ export const hooksSessionStart: MCPTool = { const restoreLatest = params.restoreLatest as boolean; const shouldStartDaemon = params.startDaemon === true; + if (params.sessionId) { const v = validateIdentifier(params.sessionId as string, 'sessionId'); if (!v.valid) return { success: false, error: v.error }; } + // Auto-regenerate statusline if outdated (fixes older installs) // Checks for the old fake heuristic: "Math.floor(sizeKB / 2)" try { @@ -1942,6 +1972,8 @@ export const hooksSessionRestore: MCPTool = { const restoreAgents = params.restoreAgents !== false; const restoreTasks = params.restoreTasks !== false; + if (params.sessionId) { const v = validateIdentifier(params.sessionId as string, 'sessionId'); if (!v.valid) return { success: false, error: v.error }; } + const originalSessionId = requestedId === 'latest' ? `session-${Date.now() - 86400000}` : requestedId; const newSessionId = `session-${Date.now()}`; @@ -1986,6 +2018,9 @@ export const hooksNotify: MCPTool = { const target = (params.target as string) || 'all'; const priority = (params.priority as string) || 'normal'; + { const v = validateText(message, 'message'); if (!v.valid) return { success: false, error: v.error }; } + if (params.target) { const v = validateIdentifier(target, 'target'); if (!v.valid) return { success: false, error: v.error }; } + return { notificationId: `notify-${Date.now()}`, message, @@ -2229,6 +2264,10 @@ export const hooksTrajectoryStart: MCPTool = { handler: async (params: Record) => { const task = params.task as string; const agent = (params.agent as string) || 'coder'; + + { const v = validateText(task, 'task'); if (!v.valid) return { success: false, error: v.error }; } + if (params.agent) { const v = validateIdentifier(params.agent as string, 'agent'); if (!v.valid) return { success: false, error: v.error }; } + const trajectoryId = `traj-${Date.now()}-${Math.random().toString(36).substring(7)}`; const startedAt = new Date().toISOString(); @@ -2276,6 +2315,9 @@ export const hooksTrajectoryStep: MCPTool = { const timestamp = new Date().toISOString(); const stepId = `step-${Date.now()}`; + { const v = validateIdentifier(trajectoryId, 'trajectoryId'); if (!v.valid) return { success: false, error: v.error }; } + { const v = validateText(action, 'action'); if (!v.valid) return { success: false, error: v.error }; } + // Add step to real trajectory if it exists const trajectory = activeTrajectories.get(trajectoryId); if (trajectory) { @@ -2315,6 +2357,9 @@ export const hooksTrajectoryEnd: MCPTool = { }, handler: async (params: Record) => { const trajectoryId = params.trajectoryId as string; + + { const v = validateIdentifier(trajectoryId, 'trajectoryId'); if (!v.valid) return { success: false, error: v.error }; } + const success = params.success !== false; const feedback = params.feedback as string | undefined; const endedAt = new Date().toISOString(); @@ -2463,6 +2508,9 @@ export const hooksPatternStore: MCPTool = { const confidence = (params.confidence as number) || 0.8; const metadata = params.metadata as Record | undefined; const timestamp = new Date().toISOString(); + + { const v = validateText(pattern, 'pattern'); if (!v.valid) return { success: false, error: v.error }; } + if (params.type) { const v = validateIdentifier(params.type as string, 'type'); if (!v.valid) return { success: false, error: v.error }; } const patternId = `pattern-${Date.now()}-${Math.random().toString(36).substring(7)}`; // Phase 3: Try ReasoningBank via bridge first @@ -2533,6 +2581,9 @@ export const hooksPatternSearch: MCPTool = { const minConfidence = (params.minConfidence as number) || 0.3; const namespace = (params.namespace as string) || 'pattern'; + { const v = validateText(query, 'query'); if (!v.valid) return { success: false, error: v.error }; } + if (params.namespace) { const v = validateIdentifier(params.namespace as string, 'namespace'); if (!v.valid) return { success: false, error: v.error }; } + // Phase 3: Try ReasoningBank search via bridge first try { const bridge = await import('../memory/memory-bridge.js'); @@ -2888,6 +2939,8 @@ export const hooksIntelligenceAttention: MCPTool = { const topK = (params.topK as number) || 5; const startTime = performance.now(); + { const v = validateText(query, 'query'); if (!v.valid) return { success: false, error: v.error }; } + let implementation = 'placeholder'; const results: Array<{ index: number; weight: number; pattern: string; expert?: string }> = []; @@ -3312,6 +3365,8 @@ export const hooksWorkerDispatch: MCPTool = { const priority = (params.priority as string) || WORKER_CONFIGS[trigger]?.priority || 'normal'; const background = params.background !== false; + if (params.context) { const v = validateText(params.context as string, 'context'); if (!v.valid) return { success: false, error: v.error }; } + if (!WORKER_CONFIGS[trigger]) { return { success: false, @@ -3403,6 +3458,8 @@ export const hooksWorkerStatus: MCPTool = { const workerId = params.workerId as string; const includeCompleted = params.includeCompleted !== false; + if (workerId) { const v = validateIdentifier(workerId, 'workerId'); if (!v.valid) return { success: false, error: v.error }; } + if (workerId) { const worker = activeWorkers.get(workerId); if (!worker) { @@ -3462,6 +3519,8 @@ export const hooksWorkerDetect: MCPTool = { const autoDispatch = params.autoDispatch as boolean; const minConfidence = (params.minConfidence as number) || 0.5; + { const v = validateText(prompt, 'prompt'); if (!v.valid) return { success: false, error: v.error }; } + const detection = detectWorkerTriggers(prompt); const result: Record = { @@ -3540,6 +3599,9 @@ export const hooksModelRoute: MCPTool = { }, handler: async (params: Record) => { const task = params.task as string; + + { const v = validateText(task, 'task'); if (!v.valid) return { success: false, error: v.error }; } + const router = await getModelRouterInstance(); if (!router) { @@ -3587,6 +3649,8 @@ export const hooksModelOutcome: MCPTool = { const model = params.model as 'haiku' | 'sonnet' | 'opus'; const outcome = params.outcome as 'success' | 'failure' | 'escalated'; + { const v = validateText(task, 'task'); if (!v.valid) return { success: false, error: v.error }; } + const router = await getModelRouterInstance(); if (router) { router.recordOutcome(task, model, outcome); @@ -3659,6 +3723,9 @@ export const hooksWorkerCancel: MCPTool = { }, handler: async (params: Record) => { const workerId = params.workerId as string; + + { const v = validateIdentifier(workerId, 'workerId'); if (!v.valid) return { success: false, error: v.error }; } + const worker = activeWorkers.get(workerId); if (!worker) { diff --git a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts index 12716425e7..815ad68bbe 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts @@ -13,6 +13,7 @@ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'fs'; import { join, resolve } from 'path'; import type { MCPTool } from './types.js'; +import { validateIdentifier } from './validate-input.js'; // Legacy JSON store interface (for migration) interface LegacyMemoryEntry { @@ -280,7 +281,7 @@ export const memoryTools: MCPTool[] = [ const key = input.key as string; const namespace = (input.namespace as string) || 'default'; - validateMemoryInput(key); + validateMemoryInput(key, undefined, undefined, namespace); try { const result = await getEntry({ key, namespace }); @@ -415,7 +416,7 @@ export const memoryTools: MCPTool[] = [ const key = input.key as string; const namespace = (input.namespace as string) || 'default'; - validateMemoryInput(key); + validateMemoryInput(key, undefined, undefined, namespace); try { const result = await deleteEntry({ key, namespace }); @@ -459,6 +460,8 @@ export const memoryTools: MCPTool[] = [ const limit = (input.limit as number) || 50; const offset = (input.offset as number) || 0; + if (namespace) { const vNs = validateIdentifier(namespace, 'namespace'); if (!vNs.valid) throw new Error(vNs.error); } + try { const result = await listEntries({ namespace, @@ -605,6 +608,7 @@ export const memoryTools: MCPTool[] = [ const { homedir } = await import('os'); const ns = (input.namespace as string) || 'claude-memories'; + if (input.namespace) { const vNs = validateIdentifier(ns, 'namespace'); if (!vNs.valid) return { success: false, imported: 0, error: vNs.error }; } const allProjects = input.allProjects as boolean; const claudeProjectsDir = join(homedir(), '.claude', 'projects'); @@ -774,6 +778,8 @@ export const memoryTools: MCPTool[] = [ const limit = (input.limit as number) || 10; const ns = input.namespace as string | undefined; + if (ns) { const vNs = validateIdentifier(ns, 'namespace'); if (!vNs.valid) return { success: false, query, results: [], total: 0, error: vNs.error }; } + // Search all namespaces unless filtered const namespaces = ns ? [ns] : ['default', 'claude-memories', 'auto-memory', 'patterns', 'tasks', 'feedback']; const allResults: Array<{ key: string; content: string; score: number; namespace: string; source: string }> = []; diff --git a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts index 72c76058b6..d86005778b 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts @@ -13,6 +13,7 @@ */ import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; @@ -184,6 +185,8 @@ export const neuralTools: MCPTool[] = [ required: ['modelType'], }, handler: async (input) => { + if (input.modelId) { const v = validateIdentifier(input.modelId as string, 'modelId'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadNeuralStore(); const modelId = (input.modelId as string) || `model-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`; const modelType = input.modelType as NeuralModel['type']; @@ -268,6 +271,9 @@ export const neuralTools: MCPTool[] = [ required: ['input'], }, handler: async (input) => { + { const v = validateText(input.input as string, 'input'); if (!v.valid) return { success: false, error: v.error }; } + if (input.modelId) { const v = validateIdentifier(input.modelId as string, 'modelId'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadNeuralStore(); const modelId = input.modelId as string; const inputText = input.input as string; @@ -333,6 +339,11 @@ export const neuralTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.patternId) { const v = validateIdentifier(input.patternId as string, 'patternId'); if (!v.valid) return { success: false, error: v.error }; } + if (input.name) { const v = validateText(input.name as string, 'name'); if (!v.valid) return { success: false, error: v.error }; } + if (input.type) { const v = validateIdentifier(input.type as string, 'type'); if (!v.valid) return { success: false, error: v.error }; } + if (input.query) { const v = validateText(input.query as string, 'query'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadNeuralStore(); const action = (input.action as string) || 'list'; @@ -447,6 +458,8 @@ export const neuralTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.modelId) { const v = validateIdentifier(input.modelId as string, 'modelId'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadNeuralStore(); const method = (input.method as string) || 'quantize'; const targetReduction = (input.targetSize as number) || 0.5; @@ -553,6 +566,8 @@ export const neuralTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.modelId) { const v = validateIdentifier(input.modelId as string, 'modelId'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadNeuralStore(); if (input.modelId) { @@ -606,6 +621,8 @@ export const neuralTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.modelId) { const v = validateIdentifier(input.modelId as string, 'modelId'); if (!v.valid) return { success: false, error: v.error }; } + const store = loadNeuralStore(); const target = (input.target as string) || 'balanced'; const patterns = Object.values(store.patterns); diff --git a/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts index 0a20ffe5a5..205fef81c2 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/performance-tools.ts @@ -13,6 +13,7 @@ */ import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier } from './validate-input.js'; import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import * as os from 'node:os'; @@ -200,6 +201,7 @@ export const performanceTools: MCPTool[] = [ }, }, handler: async (_input) => { + if (_input.component) { const v = validateIdentifier(_input.component, 'component'); if (!v.valid) return { success: false, error: v.error }; } const loadAvg = os.loadavg(); const cpus = os.cpus(); const cpuPercent = Math.min((loadAvg[0] / cpus.length) * 100, 100); @@ -404,6 +406,7 @@ export const performanceTools: MCPTool[] = [ }, }, handler: async (input) => { + if (input.target) { const v = validateIdentifier(input.target, 'target'); if (!v.valid) return { success: false, error: v.error }; } const target = (input.target as string) || 'all'; const durationSec = Math.min((input.duration as number) || 1, 10); const durationMs = durationSec * 1000; diff --git a/v3/@claude-flow/cli/src/mcp-tools/ruvllm-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/ruvllm-tools.ts index 08dfa6a3bc..5f515d109c 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/ruvllm-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/ruvllm-tools.ts @@ -6,6 +6,7 @@ */ import type { MCPTool } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; import type { ChatMessage } from '../ruvector/ruvllm-wasm.js'; async function loadRuvllmWasm() { @@ -70,6 +71,8 @@ export const ruvllmWasmTools: MCPTool[] = [ required: ['routerId', 'name', 'embedding'], }, handler: async (args: Record) => { + { const v = validateIdentifier(args.routerId, 'routerId'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } + { const v = validateIdentifier(args.name, 'name'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const router = hnswRouters.get(args.routerId as string); if (!router) return { content: [{ type: 'text', text: JSON.stringify({ error: `Router not found: ${args.routerId}` }) }], isError: true }; @@ -98,6 +101,7 @@ export const ruvllmWasmTools: MCPTool[] = [ required: ['routerId', 'query'], }, handler: async (args: Record) => { + { const v = validateIdentifier(args.routerId, 'routerId'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const router = hnswRouters.get(args.routerId as string); if (!router) return { content: [{ type: 'text', text: JSON.stringify({ error: `Router not found: ${args.routerId}` }) }], isError: true }; @@ -148,6 +152,7 @@ export const ruvllmWasmTools: MCPTool[] = [ required: ['sonaId', 'quality'], }, handler: async (args: Record) => { + { const v = validateIdentifier(args.sonaId, 'sonaId'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const sona = sonaInstances.get(args.sonaId as string); if (!sona) return { content: [{ type: 'text', text: JSON.stringify({ error: `SONA not found: ${args.sonaId}` }) }], isError: true }; @@ -202,6 +207,7 @@ export const ruvllmWasmTools: MCPTool[] = [ required: ['loraId', 'quality'], }, handler: async (args: Record) => { + { const v = validateIdentifier(args.loraId, 'loraId'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const lora = loraInstances.get(args.loraId as string); if (!lora) return { content: [{ type: 'text', text: JSON.stringify({ error: `MicroLoRA not found: ${args.loraId}` }) }], isError: true }; @@ -232,6 +238,7 @@ export const ruvllmWasmTools: MCPTool[] = [ required: ['messages', 'template'], }, handler: async (args: Record) => { + { const v = validateText(args.template, 'template', 256); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const mod = await loadRuvllmWasm(); const messages = args.messages as ChatMessage[]; diff --git a/v3/@claude-flow/cli/src/mcp-tools/security-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/security-tools.ts index c6c3d4a85d..a3c2c8cd83 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/security-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/security-tools.ts @@ -11,6 +11,7 @@ */ import type { MCPTool, MCPToolResult } from './types.js'; +import { validateText, validateIdentifier } from './validate-input.js'; import { autoInstallPackage } from './auto-install.js'; import { createRequire } from 'module'; @@ -107,6 +108,7 @@ const aidefenceScanTool: MCPTool = { required: ['input'], }, handler: async (args: Record): Promise => { + { const v = validateText(args.input, 'input'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } const input = args.input as string; const quick = args.quick as boolean; @@ -184,6 +186,7 @@ const aidefenceAnalyzeTool: MCPTool = { required: ['input'], }, handler: async (args: Record): Promise => { + { const v = validateText(args.input, 'input'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } const input = args.input as string; const searchSimilar = args.searchSimilar !== false; const k = (args.k as number) || 5; @@ -319,6 +322,9 @@ const aidefenceLearnTool: MCPTool = { required: ['input', 'wasAccurate'], }, handler: async (args: Record): Promise => { + { const v = validateText(args.input, 'input'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } + if (args.verdict) { const v = validateText(args.verdict, 'verdict'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } + if (args.threatType) { const v = validateIdentifier(args.threatType, 'threatType'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } const input = args.input as string; const wasAccurate = args.wasAccurate as boolean; const verdict = args.verdict as string | undefined; @@ -390,6 +396,7 @@ const aidefenceIsSafeTool: MCPTool = { required: ['input'], }, handler: async (args: Record): Promise => { + { const v = validateText(args.input, 'input'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } const input = args.input as string; try { @@ -431,6 +438,7 @@ const aidefenceHasPIITool: MCPTool = { required: ['input'], }, handler: async (args: Record): Promise => { + { const v = validateText(args.input, 'input'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } const input = args.input as string; try { diff --git a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts index f46f01082d..6d5ba9a050 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts @@ -7,6 +7,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, unlinkSync, statSync } from 'node:fs'; import { join } from 'node:path'; import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; // Storage paths const STORAGE_DIR = '.claude-flow'; @@ -134,6 +135,14 @@ export const sessionTools: MCPTool[] = [ required: ['name'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vName = validateText(input.name, 'name', 256); + if (!vName.valid) return { success: false, error: vName.error }; + if (input.description) { + const v = validateText(input.description, 'description'); + if (!v.valid) return { success: false, error: v.error }; + } + const sessionId = `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; // Load related data based on options @@ -187,6 +196,16 @@ export const sessionTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.sessionId) { + const v = validateIdentifier(input.sessionId, 'sessionId'); + if (!v.valid) return { success: false, error: v.error }; + } + if (input.name) { + const v = validateText(input.name, 'name', 256); + if (!v.valid) return { success: false, error: v.error }; + } + let session: SessionRecord | null = null; // Try to find by sessionId first @@ -318,6 +337,10 @@ export const sessionTools: MCPTool[] = [ required: ['sessionId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.sessionId, 'sessionId'); + if (!vId.valid) return { success: false, error: vId.error }; + const sessionId = input.sessionId as string; const path = getSessionPath(sessionId); @@ -349,6 +372,10 @@ export const sessionTools: MCPTool[] = [ required: ['sessionId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.sessionId, 'sessionId'); + if (!vId.valid) return { success: false, error: vId.error }; + const sessionId = input.sessionId as string; const session = loadSession(sessionId); diff --git a/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts index 25c066f676..90ee927d5c 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts @@ -8,6 +8,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier } from './validate-input.js'; // Swarm state persistence const SWARM_DIR = '.claude-flow/swarm'; @@ -80,6 +81,16 @@ export const swarmTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.topology) { + const v = validateIdentifier(input.topology, 'topology'); + if (!v.valid) return { success: false, error: v.error }; + } + if (input.strategy) { + const v = validateIdentifier(input.strategy, 'strategy'); + if (!v.valid) return { success: false, error: v.error }; + } + const topology = (input.topology as string) || 'hierarchical-mesh'; const maxAgents = Math.min(Math.max((input.maxAgents as number) || 15, 1), 50); const strategy = (input.strategy as string) || 'specialized'; @@ -141,6 +152,12 @@ export const swarmTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.swarmId) { + const v = validateIdentifier(input.swarmId, 'swarmId'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadSwarmStore(); const swarmId = input.swarmId as string; @@ -199,6 +216,12 @@ export const swarmTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.swarmId) { + const v = validateIdentifier(input.swarmId, 'swarmId'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadSwarmStore(); const swarmId = input.swarmId as string; @@ -254,6 +277,12 @@ export const swarmTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.swarmId) { + const v = validateIdentifier(input.swarmId, 'swarmId'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadSwarmStore(); const swarmId = input.swarmId as string; diff --git a/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts index 8fbe554db6..1f74160dee 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/system-tools.ts @@ -10,6 +10,7 @@ */ import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier } from './validate-input.js'; import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -470,6 +471,7 @@ export const systemTools: MCPTool[] = [ return { success: false, error: 'Reset requires confirmation' }; } + if (input.component) { const v = validateIdentifier(input.component, 'component'); if (!v.valid) return { success: false, error: v.error }; } const component = (input.component as string) || 'metrics'; // Reset metrics to defaults diff --git a/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts index 8cd64b70e6..8d3cbd70c8 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/task-tools.ts @@ -7,6 +7,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; // Storage paths const STORAGE_DIR = '.claude-flow'; @@ -83,6 +84,12 @@ export const taskTools: MCPTool[] = [ required: ['type', 'description'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vType = validateIdentifier(input.type, 'type'); + if (!vType.valid) return { success: false, error: vType.error }; + const vDesc = validateText(input.description, 'description'); + if (!vDesc.valid) return { success: false, error: vDesc.error }; + const store = loadTaskStore(); const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; @@ -127,6 +134,10 @@ export const taskTools: MCPTool[] = [ required: ['taskId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.taskId, 'taskId'); + if (!vId.valid) return { success: false, error: vId.error }; + const store = loadTaskStore(); const taskId = input.taskId as string; const task = store.tasks[taskId]; @@ -230,6 +241,10 @@ export const taskTools: MCPTool[] = [ required: ['taskId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.taskId, 'taskId'); + if (!vId.valid) return { success: false, error: vId.error }; + const store = loadTaskStore(); const taskId = input.taskId as string; const task = store.tasks[taskId]; @@ -293,6 +308,10 @@ export const taskTools: MCPTool[] = [ required: ['taskId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.taskId, 'taskId'); + if (!vId.valid) return { success: false, error: vId.error }; + const store = loadTaskStore(); const taskId = input.taskId as string; const task = store.tasks[taskId]; @@ -343,6 +362,10 @@ export const taskTools: MCPTool[] = [ required: ['taskId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.taskId, 'taskId'); + if (!vId.valid) return { success: false, error: vId.error }; + const store = loadTaskStore(); const taskId = input.taskId as string; const task = store.tasks[taskId]; @@ -426,6 +449,14 @@ export const taskTools: MCPTool[] = [ required: ['taskId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.taskId, 'taskId'); + if (!vId.valid) return { success: false, error: vId.error }; + if (input.reason) { + const v = validateText(input.reason, 'reason'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadTaskStore(); const taskId = input.taskId as string; const task = store.tasks[taskId]; diff --git a/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts index 23b457079b..97eeee55ee 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts @@ -6,6 +6,7 @@ import { type MCPTool, getProjectCwd } from './types.js'; import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; +import { validateIdentifier, validatePath, validateText } from './validate-input.js'; import { join } from 'node:path'; import { execSync } from 'node:child_process'; @@ -76,6 +77,16 @@ export const terminalTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.name) { + const v = validateText(input.name, 'name', 256); + if (!v.valid) return { success: false, error: v.error }; + } + if (input.workingDir) { + const v = validatePath(input.workingDir, 'workingDir'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadTerminalStore(); const id = `term-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; @@ -118,6 +129,14 @@ export const terminalTools: MCPTool[] = [ required: ['command'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vCmd = validateText(input.command, 'command', 10_000); + if (!vCmd.valid) return { success: false, error: vCmd.error }; + if (input.sessionId) { + const v = validateIdentifier(input.sessionId, 'sessionId'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadTerminalStore(); const sessionId = input.sessionId as string; const command = input.command as string; @@ -236,6 +255,10 @@ export const terminalTools: MCPTool[] = [ required: ['sessionId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.sessionId, 'sessionId'); + if (!vId.valid) return { success: false, error: vId.error }; + const store = loadTerminalStore(); const sessionId = input.sessionId as string; const session = store.sessions[sessionId]; @@ -267,6 +290,12 @@ export const terminalTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.sessionId) { + const v = validateIdentifier(input.sessionId, 'sessionId'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadTerminalStore(); const sessionId = input.sessionId as string; const limit = (input.limit as number) || 50; diff --git a/v3/@claude-flow/cli/src/mcp-tools/transfer-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/transfer-tools.ts index 539e2c6b06..a26340a87b 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/transfer-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/transfer-tools.ts @@ -7,6 +7,7 @@ */ import type { MCPTool, MCPToolResult } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; /** * Helper to create MCP tool result @@ -46,6 +47,7 @@ export const transferTools: MCPTool[] = [ required: ['content'], }, handler: async (input): Promise => { + { const v = validateText((input as { content: string }).content, 'content'); if (!v.valid) return createResult({ error: v.error }, true); } try { const { detectPII } = await import('../transfer/anonymization/index.js'); const result = detectPII((input as { content: string }).content); @@ -75,6 +77,7 @@ export const transferTools: MCPTool[] = [ required: ['name'], }, handler: async (input): Promise => { + { const v = validateIdentifier((input as { name: string }).name, 'name'); if (!v.valid) return createResult({ error: v.error }, true); } try { const { resolveIPNS } = await import('../transfer/ipfs/client.js'); const result = await resolveIPNS((input as { name: string }).name); @@ -119,6 +122,8 @@ export const transferTools: MCPTool[] = [ }, }, handler: async (input): Promise => { + if ((input as Record).query) { const v = validateText((input as Record).query, 'query'); if (!v.valid) return createResult({ error: v.error }, true); } + if ((input as Record).category) { const v = validateIdentifier((input as Record).category, 'category'); if (!v.valid) return createResult({ error: v.error }, true); } try { const { PatternStore } = await import('../transfer/store/index.js'); const store = new PatternStore(); @@ -147,6 +152,7 @@ export const transferTools: MCPTool[] = [ required: ['id'], }, handler: async (input): Promise => { + { const v = validateIdentifier((input as { id: string }).id, 'id'); if (!v.valid) return createResult({ error: v.error }, true); } try { const { PatternStore } = await import('../transfer/store/index.js'); const store = new PatternStore(); @@ -182,6 +188,7 @@ export const transferTools: MCPTool[] = [ required: ['id'], }, handler: async (input): Promise => { + { const v = validateIdentifier((input as { id: string }).id, 'id'); if (!v.valid) return createResult({ error: v.error }, true); } try { const { PatternStore } = await import('../transfer/store/index.js'); const store = new PatternStore(); @@ -291,6 +298,9 @@ export const transferTools: MCPTool[] = [ }, }, handler: async (input): Promise => { + if ((input as Record).query) { const v = validateText((input as Record).query, 'query'); if (!v.valid) return createResult({ error: v.error }, true); } + if ((input as Record).category) { const v = validateIdentifier((input as Record).category, 'category'); if (!v.valid) return createResult({ error: v.error }, true); } + if ((input as Record).type) { const v = validateIdentifier((input as Record).type, 'type'); if (!v.valid) return createResult({ error: v.error }, true); } try { const { createPluginDiscoveryService, searchPlugins } = await import( '../plugins/store/index.js' @@ -325,6 +335,7 @@ export const transferTools: MCPTool[] = [ required: ['name'], }, handler: async (input): Promise => { + { const v = validateIdentifier((input as { name: string }).name, 'name'); if (!v.valid) return createResult({ error: v.error }, true); } try { const { createPluginDiscoveryService } = await import('../plugins/store/index.js'); const discovery = createPluginDiscoveryService(); diff --git a/v3/@claude-flow/cli/src/mcp-tools/wasm-agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/wasm-agent-tools.ts index 5f7d5f61f9..c73399167a 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/wasm-agent-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/wasm-agent-tools.ts @@ -6,6 +6,7 @@ */ import type { MCPTool } from './types.js'; +import { validateIdentifier, validateText } from './validate-input.js'; async function loadAgentWasm() { const mod = await import('../ruvector/agent-wasm.js'); @@ -26,6 +27,9 @@ export const wasmAgentTools: MCPTool[] = [ }, }, handler: async (args: Record) => { + if (args.template) { const v = validateIdentifier(args.template, 'template'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } + if (args.model) { const v = validateIdentifier(args.model, 'model'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } + if (args.instructions) { const v = validateText(args.instructions, 'instructions'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const wasm = await loadAgentWasm(); if (args.template) { @@ -55,6 +59,8 @@ export const wasmAgentTools: MCPTool[] = [ required: ['agentId', 'input'], }, handler: async (args: Record) => { + { const v = validateIdentifier(args.agentId, 'agentId'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } + { const v = validateText(args.input, 'input'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const wasm = await loadAgentWasm(); const result = await wasm.promptWasmAgent(args.agentId as string, args.input as string); @@ -77,6 +83,8 @@ export const wasmAgentTools: MCPTool[] = [ required: ['agentId', 'toolName'], }, handler: async (args: Record) => { + { const v = validateIdentifier(args.agentId, 'agentId'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } + { const v = validateIdentifier(args.toolName, 'toolName'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const wasm = await loadAgentWasm(); // Flat format: {tool: 'write_file', path: '...', content: '...'} @@ -116,6 +124,7 @@ export const wasmAgentTools: MCPTool[] = [ required: ['agentId'], }, handler: async (args: Record) => { + { const v = validateIdentifier(args.agentId, 'agentId'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const wasm = await loadAgentWasm(); const ok = wasm.terminateWasmAgent(args.agentId as string); @@ -136,6 +145,7 @@ export const wasmAgentTools: MCPTool[] = [ required: ['agentId'], }, handler: async (args: Record) => { + { const v = validateIdentifier(args.agentId, 'agentId'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const wasm = await loadAgentWasm(); const tools = wasm.getWasmAgentTools(args.agentId as string); @@ -157,6 +167,7 @@ export const wasmAgentTools: MCPTool[] = [ required: ['agentId'], }, handler: async (args: Record) => { + { const v = validateIdentifier(args.agentId, 'agentId'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const wasm = await loadAgentWasm(); const state = wasm.exportWasmState(args.agentId as string); @@ -191,6 +202,7 @@ export const wasmAgentTools: MCPTool[] = [ required: ['query'], }, handler: async (args: Record) => { + { const v = validateText(args.query, 'query'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const wasm = await loadAgentWasm(); const results = await wasm.searchGalleryTemplates(args.query as string); @@ -211,6 +223,7 @@ export const wasmAgentTools: MCPTool[] = [ required: ['template'], }, handler: async (args: Record) => { + { const v = validateIdentifier(args.template, 'template'); if (!v.valid) return { content: [{ type: 'text', text: JSON.stringify({ error: v.error }) }], isError: true }; } try { const wasm = await loadAgentWasm(); const info = await wasm.createAgentFromTemplate(args.template as string); diff --git a/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts index aaeae4acbe..04ca006496 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/workflow-tools.ts @@ -7,6 +7,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { type MCPTool, getProjectCwd } from './types.js'; +import { validateIdentifier, validatePath, validateText } from './validate-input.js'; // Storage paths const STORAGE_DIR = '.claude-flow'; @@ -101,6 +102,20 @@ export const workflowTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.template) { + const v = validateIdentifier(input.template, 'template'); + if (!v.valid) return { success: false, error: v.error }; + } + if (input.file) { + const v = validatePath(input.file, 'file'); + if (!v.valid) return { success: false, error: v.error }; + } + if (input.task) { + const v = validateText(input.task, 'task'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadWorkflowStore(); const template = input.template as string | undefined; const task = input.task as string | undefined; @@ -202,6 +217,14 @@ export const workflowTools: MCPTool[] = [ required: ['name'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vName = validateText(input.name, 'name', 256); + if (!vName.valid) return { success: false, error: vName.error }; + if (input.description) { + const v = validateText(input.description, 'description'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadWorkflowStore(); const workflowId = `workflow-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; @@ -250,6 +273,10 @@ export const workflowTools: MCPTool[] = [ required: ['workflowId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.workflowId, 'workflowId'); + if (!vId.valid) return { success: false, error: vId.error }; + const store = loadWorkflowStore(); const workflowId = input.workflowId as string; const workflow = store.workflows[workflowId]; @@ -309,6 +336,10 @@ export const workflowTools: MCPTool[] = [ required: ['workflowId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.workflowId, 'workflowId'); + if (!vId.valid) return { success: false, error: vId.error }; + const store = loadWorkflowStore(); const workflowId = input.workflowId as string; const workflow = store.workflows[workflowId]; @@ -365,6 +396,12 @@ export const workflowTools: MCPTool[] = [ }, }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.status) { + const v = validateIdentifier(input.status, 'status'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadWorkflowStore(); let workflows = Object.values(store.workflows); @@ -406,6 +443,10 @@ export const workflowTools: MCPTool[] = [ required: ['workflowId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.workflowId, 'workflowId'); + if (!vId.valid) return { success: false, error: vId.error }; + const store = loadWorkflowStore(); const workflowId = input.workflowId as string; const workflow = store.workflows[workflowId]; @@ -441,6 +482,10 @@ export const workflowTools: MCPTool[] = [ required: ['workflowId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.workflowId, 'workflowId'); + if (!vId.valid) return { success: false, error: vId.error }; + const store = loadWorkflowStore(); const workflowId = input.workflowId as string; const workflow = store.workflows[workflowId]; @@ -489,6 +534,14 @@ export const workflowTools: MCPTool[] = [ required: ['workflowId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.workflowId, 'workflowId'); + if (!vId.valid) return { success: false, error: vId.error }; + if (input.reason) { + const v = validateText(input.reason, 'reason'); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadWorkflowStore(); const workflowId = input.workflowId as string; const workflow = store.workflows[workflowId]; @@ -533,6 +586,10 @@ export const workflowTools: MCPTool[] = [ required: ['workflowId'], }, handler: async (input) => { + // Validate user-provided input (#1425) + const vId = validateIdentifier(input.workflowId, 'workflowId'); + if (!vId.valid) return { success: false, error: vId.error }; + const store = loadWorkflowStore(); const workflowId = input.workflowId as string; @@ -571,6 +628,24 @@ export const workflowTools: MCPTool[] = [ required: ['action'], }, handler: async (input) => { + // Validate user-provided input (#1425) + if (input.workflowId) { + const v = validateIdentifier(input.workflowId, 'workflowId'); + if (!v.valid) return { success: false, error: v.error }; + } + if (input.templateId) { + const v = validateIdentifier(input.templateId, 'templateId'); + if (!v.valid) return { success: false, error: v.error }; + } + if (input.templateName) { + const v = validateText(input.templateName, 'templateName', 256); + if (!v.valid) return { success: false, error: v.error }; + } + if (input.newName) { + const v = validateText(input.newName, 'newName', 256); + if (!v.valid) return { success: false, error: v.error }; + } + const store = loadWorkflowStore(); const action = input.action as string; diff --git a/v3/@claude-flow/cli/src/memory/intelligence.ts b/v3/@claude-flow/cli/src/memory/intelligence.ts index 9945aad4f8..e0dc7ab879 100644 --- a/v3/@claude-flow/cli/src/memory/intelligence.ts +++ b/v3/@claude-flow/cli/src/memory/intelligence.ts @@ -451,7 +451,9 @@ class LocalReasoningBank { } /** - * Load patterns from disk + * Load patterns from disk, deduplicating by content. + * When multiple patterns share identical content, keeps the one with + * highest confidence (ties broken by most recent lastUsedAt). */ private loadFromDisk(): void { try { @@ -459,10 +461,44 @@ class LocalReasoningBank { if (existsSync(path)) { const data = JSON.parse(readFileSync(path, 'utf-8')); if (Array.isArray(data)) { + const totalLoaded = data.length; + + // Group by content to deduplicate + const byContent = new Map(); for (const pattern of data) { + const key = pattern.content; + const existing = byContent.get(key); + if (!existing) { + byContent.set(key, pattern); + } else { + // Keep the one with higher confidence; break ties by lastUsedAt + if ( + pattern.confidence > existing.confidence || + (pattern.confidence === existing.confidence && + (pattern.lastUsedAt ?? 0) > (existing.lastUsedAt ?? 0)) + ) { + // Merge: adopt the higher usageCount sum + pattern.usageCount = (pattern.usageCount ?? 0) + (existing.usageCount ?? 0); + byContent.set(key, pattern); + } else { + existing.usageCount = (existing.usageCount ?? 0) + (pattern.usageCount ?? 0); + } + } + } + + // Populate the bank from deduplicated entries + for (const pattern of byContent.values()) { this.patterns.set(pattern.id, pattern); this.patternList.push(pattern); } + + const removed = totalLoaded - byContent.size; + if (removed > 0) { + console.log(`Deduplicated ${removed} patterns (${byContent.size} unique)`); + // Persist the compacted set immediately so the file shrinks on disk + this.dirty = true; + this.flushToDisk(); + } } } } catch { @@ -507,6 +543,9 @@ class LocalReasoningBank { /** * Store a pattern - O(1) + * Deduplicates by content: if a pattern with the same content already + * exists, the existing entry is updated (bumped usageCount, higher + * confidence wins, refreshed lastUsedAt) instead of adding a duplicate. */ store(pattern: Omit & Partial): void { const now = Date.now(); @@ -529,6 +568,21 @@ class LocalReasoningBank { this.patternList[idx] = stored; } } else { + // Check for content-duplicate before inserting a new entry + const contentDupe = this.patternList.find(p => p.content === pattern.content); + if (contentDupe) { + // Merge into the existing pattern instead of adding a duplicate + contentDupe.usageCount++; + contentDupe.lastUsedAt = now; + if (stored.confidence > contentDupe.confidence) { + contentDupe.confidence = stored.confidence; + } + // Keep the Map in sync with the mutated object + this.patterns.set(contentDupe.id, contentDupe); + this.saveToDisk(); + return; + } + // Evict oldest if at capacity if (this.patterns.size >= this.maxSize) { const oldest = this.patternList.shift(); diff --git a/v3/@claude-flow/cli/vitest.config.ts b/v3/@claude-flow/cli/vitest.config.ts index 748d9a2d43..b79bcdd2ba 100644 --- a/v3/@claude-flow/cli/vitest.config.ts +++ b/v3/@claude-flow/cli/vitest.config.ts @@ -1,11 +1,25 @@ import { defineConfig } from 'vitest/config'; export default defineConfig({ + resolve: { + conditions: ['node'], + }, + plugins: [ + { + name: 'externalize-optional-deps', + enforce: 'pre', + resolveId(source) { + // Don't let Vite resolve optional deps that may have missing subpath exports + if (source.startsWith('agentic-flow')) return { id: source, external: true }; + if (source.startsWith('agentdb')) return { id: source, external: true }; + return null; + }, + }, + ], test: { environment: 'node', include: ['__tests__/**/*.test.ts'], globals: true, - // Disable coverage for CLI package (uses vitest v2) coverage: { enabled: false, }, diff --git a/v3/@claude-flow/integration/package.json b/v3/@claude-flow/integration/package.json index 7d47351aee..10c7bb33e8 100644 --- a/v3/@claude-flow/integration/package.json +++ b/v3/@claude-flow/integration/package.json @@ -40,7 +40,7 @@ "optionalComponents": { "TokenOptimizer": { "description": "Token reduction via agentic-flow Agent Booster integration", - "savings": "30-50%", + "savings": "varies (depends on ReasoningBank cache hit rate and query patterns)", "features": [ "ReasoningBank", "cache", diff --git a/v3/@claude-flow/integration/src/token-optimizer.ts b/v3/@claude-flow/integration/src/token-optimizer.ts index fd4455c642..6720768a42 100644 --- a/v3/@claude-flow/integration/src/token-optimizer.ts +++ b/v3/@claude-flow/integration/src/token-optimizer.ts @@ -2,10 +2,13 @@ * Token Optimizer - Integrates agentic-flow Agent Booster capabilities * * Combines: - * - Agent Booster (352x code edit speedup) - * - ReasoningBank (32% token reduction via semantic retrieval) + * - Agent Booster (code edit speedup via WASM, if available) + * - ReasoningBank (token reduction via semantic retrieval, savings vary by query) * - Configuration Tuning (batch/cache/topology optimization) * + * Note: Actual savings depend on agentic-flow availability and usage patterns. + * No fabricated metrics are reported -- all stats reflect real measurements. + * * @module v3/integration/token-optimizer */ @@ -42,7 +45,8 @@ async function safeImport(modulePath: string): Promise { } /** - * Token Optimizer - Reduces token usage via agentic-flow integration + * Token Optimizer - Measures and reports token usage via agentic-flow integration. + * All reported statistics reflect actual measured values, not estimates. */ export class TokenOptimizer extends EventEmitter { private stats = { @@ -99,8 +103,8 @@ export class TokenOptimizer extends EventEmitter { } /** - * Retrieve compact context instead of full file content - * Saves ~32% tokens via semantic retrieval + * Retrieve compact context instead of full file content. + * Token savings depend on query length vs retrieved context size. */ async getCompactContext(query: string, options?: { limit?: number; @@ -144,8 +148,8 @@ export class TokenOptimizer extends EventEmitter { } /** - * Optimized code edit using Agent Booster (352x faster) - * Faster edits = fewer timeouts = fewer retry tokens + * Optimized code edit using Agent Booster (if available). + * Faster edits may reduce timeouts and retry tokens. */ async optimizedEdit( filePath: string, @@ -218,8 +222,8 @@ export class TokenOptimizer extends EventEmitter { } /** - * Cache-aware embedding lookup - * 95% hit rate = 95% fewer embedding API calls + * Cache-aware embedding lookup. + * Cache hit rate depends on query patterns and TTL (5 min default). */ async cachedLookup(key: string, generator: () => Promise): Promise { // Use local cache if configTuning not available diff --git a/v3/docs/adr/ADR-085-issue-1425-comprehensive-remediation.md b/v3/docs/adr/ADR-085-issue-1425-comprehensive-remediation.md new file mode 100644 index 0000000000..cc96ac5f07 --- /dev/null +++ b/v3/docs/adr/ADR-085-issue-1425-comprehensive-remediation.md @@ -0,0 +1,48 @@ +# ADR-085: Comprehensive Remediation of Issue #1425 + +## Status +Accepted + +## Context + +Issue [#1425](https://github.com/ruvnet/ruflo/issues/1425) identified systemic quality problems in the codebase, independently confirmed by an external audit. After initial fixes in v3.5.43 (PR #1435, ADR-067) and v3.5.69, the following items remain unresolved in v3: + +1. **~19 `any` types in v3 CLI commands** β€” TypeScript type safety gaps +2. **3 websocket implementations** β€” CLI, hooks, and MCP bridge each have separate WS logic with different auth and reconnection behavior +3. **3 agent management systems** β€” AgentManager, WorkerPool, and MCP agent tools don't share code or coordinate state +4. **Providers `list`/`test` static catalog** β€” Returns hardcoded provider list, ignores user configuration +5. **Security validators on only 2 of 43 endpoints** β€” `validate-input.ts` wired to `agent_spawn` and `memory_store` only +6. **Token Optimizer `sleep(352)` baseline** β€” Benchmark uses artificial delay as timing baseline +7. **Intelligence layer processes ~5,706 entries with ~20 unique** β€” No dedup/compaction on session start + +## Decision + +Address all 7 items in a single release (v3.5.70): + +### 1. Eliminate `any` types in v3 commands +Replace all 19 `any` casts in `v3/@claude-flow/cli/src/commands/` with proper types. Use `unknown` + narrowing where the actual type is unclear. + +### 2. Consolidate websocket implementations +Create `v3/@claude-flow/shared/src/ws/` shared websocket module with unified auth, reconnection logic, and heartbeat. CLI, hooks, and MCP bridge import from shared module. + +### 3. Unify agent management state +Create shared `AgentRegistry` in `@claude-flow/shared` that AgentManager, WorkerPool, and MCP agent tools all use. Single source of truth for agent lifecycle. + +### 4. Wire providers to config +`providers list` reads from `claude-flow.config.json` or environment. `providers test` makes real API health check calls (with timeout). + +### 5. Expand input validation to all command handlers +Add `validateIdentifier`/`validatePath`/`validateText` calls to all 43 command handlers that accept user input. Focus on boundary inputs: file paths, identifiers, command arguments. + +### 6. Fix Token Optimizer benchmark +Remove `sleep(352)` artificial baseline. Benchmark against actual no-op timing. Remove hardcoded `+= 100` token savings β€” measure real token counts or remove the claim. + +### 7. Intelligence layer dedup on session start +Add compaction pass in `session-start` hook that deduplicates entries by content hash before building the graph. Skip entries with identical content, keeping highest confidence version. + +## Consequences + +- All critical items from #1425 and the independent audit are resolved +- v3 CLI has proper type safety, consolidated infrastructure, and honest metrics +- Input validation covers all user-facing entry points +- Larger architectural items (#2 WS, #3 agent management) get shared modules that benefit future development diff --git a/v3/package-lock.json b/v3/package-lock.json index d2f88832f6..8425845984 100644 --- a/v3/package-lock.json +++ b/v3/package-lock.json @@ -1789,7 +1789,7 @@ } }, "@claude-flow/cli": { - "version": "3.5.69", + "version": "3.5.71", "hasInstallScript": true, "license": "MIT", "dependencies": {