Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

Checkpoint: File edits

rUv2f3f0d554d75
diff --git a/CLAUDE.md b/CLAUDE.md
index 625b30f115..0a33c8b6ec 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,4 +1,91 @@
-# Claude Code Configuration - SPARC Development Environment
+# Claude Code Configuration - Claude Flow V3
+
+## 🚨 AUTOMATIC SWARM ORCHESTRATION
+
+**When starting work on complex tasks, Claude Code MUST automatically:**
+
+1. **Initialize the swarm** using MCP tools
+2. **Spawn concurrent agents** using Claude Code's Task tool
+3. **Coordinate via hooks** and memory
+
+### 🚨 CRITICAL: MCP + Task Tool in SAME Message
+
+**When user says "spawn swarm" or requests complex work, Claude Code MUST in ONE message:**
+1. Call MCP tools to initialize coordination
+2. **IMMEDIATELY** call Task tool to spawn REAL working agents
+3. Both MCP and Task calls must be in the SAME response
+
+**MCP alone does NOT execute work - Task tool agents do the actual work!**
+
+### πŸ”„ Auto-Start Swarm Protocol
+
+When the user requests a complex task (multi-file changes, feature implementation, refactoring), **immediately execute this pattern in a SINGLE message:**
+
+```javascript
+// STEP 1: Initialize swarm coordination via MCP (in parallel with agent spawning)
+mcp__claude-flow__swarm_init({
+ topology: "hierarchical",
+ maxAgents: 15,
+ strategy: "adaptive"
+})
+
+// STEP 2: Spawn agents concurrently using Claude Code's Task tool
+// ALL Task calls MUST be in the SAME message for parallel execution
+Task("Coordinator", "You are the swarm coordinator. Initialize session, coordinate other agents via memory. Run: npx claude-flow@v3alpha hooks session-start", "hierarchical-coordinator")
+Task("Researcher", "Analyze requirements and existing code patterns. Store findings in memory via hooks.", "researcher")
+Task("Architect", "Design implementation approach based on research. Document decisions in memory.", "system-architect")
+Task("Coder", "Implement the solution following architect's design. Coordinate via hooks.", "coder")
+Task("Tester", "Write tests for the implementation. Report coverage via hooks.", "tester")
+Task("Reviewer", "Review code quality and security. Document findings.", "reviewer")
+
+// STEP 3: Batch all todos
+TodoWrite({ todos: [
+ {content: "Initialize swarm coordination", status: "in_progress", activeForm: "Initializing swarm"},
+ {content: "Research and analyze requirements", status: "in_progress", activeForm: "Researching requirements"},
+ {content: "Design architecture", status: "pending", activeForm: "Designing architecture"},
+ {content: "Implement solution", status: "pending", activeForm: "Implementing solution"},
+ {content: "Write tests", status: "pending", activeForm: "Writing tests"},
+ {content: "Review and finalize", status: "pending", activeForm: "Reviewing code"}
+]})
+
+// STEP 4: Store swarm state in memory
+mcp__claude-flow__memory_usage({
+ action: "store",
+ namespace: "swarm",
+ key: "current-session",
+ value: JSON.stringify({task: "[user's task]", agents: 6, startedAt: new Date().toISOString()})
+})
+```
+
+### πŸ“‹ Agent Routing by Task Type
+
+| Task Type | Required Agents | Topology |
+|-----------|-----------------|----------|
+| Bug Fix | researcher, coder, tester | mesh |
+| New Feature | coordinator, architect, coder, tester, reviewer | hierarchical |
+| Refactoring | architect, coder, reviewer | mesh |
+| Performance | researcher, performance-engineer, coder | hierarchical |
+| Security Audit | security-architect, security-auditor, reviewer | hierarchical |
+| Memory Optimization | memory-specialist, performance-engineer | mesh |
+| Documentation | researcher, api-docs | mesh |
+
+### 🎯 Task Complexity Detection
+
+**AUTO-INVOKE SWARM when task involves:**
+- Multiple files (3+)
+- New feature implementation
+- Refactoring across modules
+- API changes with tests
+- Security-related changes
+- Performance optimization
+- Database schema changes
+
+**SKIP SWARM for:**
+- Single file edits
+- Simple bug fixes (1-2 lines)
+- Documentation updates
+- Configuration changes
+- Quick questions/exploration
## 🚨 CRITICAL: CONCURRENT EXECUTION & FILE MANAGEMENT
@@ -17,24 +104,6 @@
- **Bash commands**: ALWAYS batch ALL terminal operations in ONE message
- **Memory operations**: ALWAYS batch ALL memory store/retrieve in ONE message
-### 🎯 CRITICAL: Claude Code Task Tool for Agent Execution
-
-**Claude Code's Task tool is the PRIMARY way to spawn agents:**
-```javascript
-// βœ… CORRECT: Use Claude Code's Task tool for parallel agent execution
-[Single Message]:
- Task("Research agent", "Analyze requirements and patterns...", "researcher")
- Task("Coder agent", "Implement core features...", "coder")
- Task("Tester agent", "Create comprehensive tests...", "tester")
- Task("Reviewer agent", "Review code quality...", "reviewer")
- Task("Architect agent", "Design system architecture...", "system-architect")
-```
-
-**MCP tools are ONLY for coordination setup:**
-- `mcp__claude-flow__swarm_init` - Initialize coordination topology
-- `mcp__claude-flow__agent_spawn` - Define agent types for coordination
-- `mcp__claude-flow__task_orchestrate` - Orchestrate high-level workflows
-
### πŸ“ File Organization Rules
**NEVER save to root folder. Use these directories:**
@@ -45,50 +114,89 @@
- `/scripts` - Utility scripts
- `/examples` - Example code
-## Project Overview
+## Project Configuration
-This project uses SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) methodology with Claude-Flow orchestration for systematic Test-Driven Development.
+This project is configured with Claude Flow V3:
+- **Topology**: hierarchical
+- **Max Agents**: 15
+- **Memory Backend**: hybrid (SQLite + AgentDB)
+- **HNSW Indexing**: Enabled (150x-12,500x faster)
+- **Neural Learning**: Enabled (SONA)
-## SPARC Commands
+## πŸš€ V3 CLI Commands (26 Commands, 140+ Subcommands)
### Core Commands
-- `npx claude-flow sparc modes` - List available modes
-- `npx claude-flow sparc run <mode> "<task>"` - Execute specific mode
-- `npx claude-flow sparc tdd "<feature>"` - Run complete TDD workflow
-- `npx claude-flow sparc info <mode>` - Get mode details
-### Batchtools Commands
-- `npx claude-flow sparc batch <modes> "<task>"` - Parallel execution
-- `npx claude-flow sparc pipeline "<task>"` - Full pipeline processing
-- `npx claude-flow sparc concurrent <mode> "<tasks-file>"` - Multi-task processing
+| Command | Subcommands | Description |
+|---------|-------------|-------------|
+| `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) |
+| `mcp` | 9 | MCP server management and tool execution |
+| `task` | 6 | Task creation, assignment, and lifecycle |
+| `session` | 7 | Session state management and persistence |
+| `config` | 7 | Configuration management and provider setup |
+| `status` | 3 | System status monitoring with watch mode |
+| `start` | 3 | Service startup and quick launch |
+| `workflow` | 6 | Workflow execution and template management |
+| `hooks` | 17 | Self-learning hooks + 12 background workers |
+| `hive-mind` | 6 | Queen-led Byzantine fault-tolerant consensus |
+
+### Advanced Commands
+
+| Command | Subcommands | Description |
+|---------|-------------|-------------|
+| `daemon` | 5 | Background worker daemon (start, stop, status, trigger, enable) |
+| `neural` | 5 | Neural pattern training (train, status, patterns, predict, optimize) |
+| `security` | 6 | Security scanning (scan, audit, cve, threats, validate, report) |
+| `performance` | 5 | Performance profiling (benchmark, profile, metrics, optimize, report) |
+| `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 |
+| `claims` | 4 | Claims-based authorization (check, grant, revoke, list) |
+| `migrate` | 5 | V2 to V3 migration with rollback support |
+| `process` | 4 | Background process management |
+| `doctor` | 1 | System diagnostics with health checks |
+| `completions` | 4 | Shell completions (bash, zsh, fish, powershell) |
+
+### Quick CLI Examples
+
+```bash
+# Initialize project
+npx claude-flow@v3alpha init --wizard
-### Build Commands
-- `npm run build` - Build project
-- `npm run test` - Run tests
-- `npm run lint` - Linting
-- `npm run typecheck` - Type checking
+# Start daemon with background workers
+npx claude-flow@v3alpha daemon start
-## SPARC Workflow Phases
+# Spawn an agent
+npx claude-flow@v3alpha agent spawn -t coder --name my-coder
-1. **Specification** - Requirements analysis (`sparc run spec-pseudocode`)
-2. **Pseudocode** - Algorithm design (`sparc run spec-pseudocode`)
-3. **Architecture** - System design (`sparc run architect`)
-4. **Refinement** - TDD implementation (`sparc tdd`)
-5. **Completion** - Integration (`sparc run integration`)
+# Initialize swarm
+npx claude-flow@v3alpha swarm init --v3-mode
-## Code Style & Best Practices
+# Search memory (HNSW-indexed)
+npx claude-flow@v3alpha memory search -q "authentication patterns"
-- **Modular Design**: Files under 500 lines
-- **Environment Safety**: Never hardcode secrets
-- **Test-First**: Write tests before implementation
-- **Clean Architecture**: Separate concerns
-- **Documentation**: Keep updated
+# System diagnostics
+npx claude-flow@v3alpha doctor --fix
-## πŸš€ Available Agents (54 Total)
+# Security scan
+npx claude-flow@v3alpha security scan --depth full
+
+# Performance benchmark
+npx claude-flow@v3alpha performance benchmark --suite all
+```
+
+## πŸš€ Available Agents (60+ Types)
### Core Development
`coder`, `reviewer`, `tester`, `planner`, `researcher`
+### V3 Specialized Agents
+`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`
+
### Swarm Coordination
`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`, `collective-intelligence-coordinator`, `swarm-memory-manager`
@@ -110,458 +218,187 @@ This project uses SPARC (Specification, Pseudocode, Architecture, Refinement, Co
### Testing & Validation
`tdd-london-swarm`, `production-validator`
-### Migration & Planning
-`migration-planner`, `swarm-init`
-
-## 🎯 Claude Code vs MCP Tools
-
-### Claude Code Handles ALL EXECUTION:
-- **Task tool**: Spawn and run agents concurrently for actual work
-- File operations (Read, Write, Edit, MultiEdit, Glob, Grep)
-- Code generation and programming
-- Bash commands and system operations
-- Implementation work
-- Project navigation and analysis
-- TodoWrite and task management
-- Git operations
-- Package management
-- Testing and debugging
-
-### MCP Tools ONLY COORDINATE:
-- Swarm initialization (topology setup)
-- Agent type definitions (coordination patterns)
-- Task orchestration (high-level planning)
-- Memory management
-- Neural features
-- Performance tracking
-- GitHub integration
-
-**KEY**: MCP coordinates the strategy, Claude Code's Task tool executes with real agents.
-
-## πŸ€– AUTOMATIC SWARM ORCHESTRATION
-
-**Claude Code MUST automatically invoke swarm orchestration for complex tasks.**
-
-### 🚨 CRITICAL: MCP + Task Tool in SAME Message
-
-**When user says "spawn swarm" or requests complex work, Claude Code MUST in ONE message:**
-1. Call MCP tools to initialize coordination
-2. **IMMEDIATELY** call Task tool to spawn REAL working agents
-3. Both MCP and Task calls must be in the SAME response
-
-**MCP alone does NOT execute work - Task tool agents do the actual work!**
-
-### Auto-Start Swarm Protocol
-
-When Claude Code detects a complex task (multi-file, new feature, or refactoring), it MUST:
-
-```javascript
-// 🚨 ALL OF THIS IN ONE SINGLE MESSAGE - MCP + Task + TodoWrite together!
-[Single Message - Complete Swarm Spawn]:
-
- // MCP: Initialize coordination topology
- mcp__claude-flow__swarm_init { topology: "hierarchical-mesh", maxAgents: 15, strategy: "adaptive" }
- mcp__claude-flow__agent_spawn { type: "coordinator", name: "queen" }
- mcp__claude-flow__task_orchestrate { task: "[user's task]", strategy: "adaptive", priority: "high" }
- mcp__claude-flow__memory_usage { action: "store", namespace: "swarm", key: "session", value: "..." }
-
- // Task Tool: Spawn REAL working agents (THIS IS REQUIRED!)
- Task("Coordinator", "Orchestrate the swarm, manage agent coordination...", "hierarchical-coordinator")
- Task("Architect", "Design system architecture, document decisions...", "system-architect")
- Task("Researcher", "Analyze requirements, research patterns...", "researcher")
- Task("Coder", "Implement core features following architecture...", "coder")
- Task("Tester", "Create comprehensive test suite...", "tester")
- Task("Reviewer", "Review code quality and security...", "reviewer")
-
- // TodoWrite: Track all tasks
- TodoWrite { todos: [
- {content: "Initialize swarm coordination", status: "completed", activeForm: "Initializing"},
- {content: "Research requirements", status: "in_progress", activeForm: "Researching"},
- {content: "Design architecture", status: "in_progress", activeForm: "Designing"},
- {content: "Implement solution", status: "pending", activeForm: "Implementing"},
- {content: "Write tests", status: "pending", activeForm: "Testing"},
- {content: "Review code", status: "pending", activeForm: "Reviewing"}
- ]}
-```
-
-**❌ WRONG - MCP only (no actual work happens):**
-```javascript
-// This ONLY sets up coordination - no agents actually work!
-mcp__claude-flow__swarm_init { ... }
-mcp__claude-flow__agent_spawn { ... }
-// Missing Task tool calls = nothing executes!
-```
-
-**βœ… CORRECT - MCP + Task tool together:**
-```javascript
-// Same message: coordination + execution
-mcp__claude-flow__swarm_init { ... }
-Task("Agent1", "Do actual work...", "agent-type")
-Task("Agent2", "Do actual work...", "agent-type")
-```
-
-### Agent Routing by Task Type
-
-| Task Type | Primary Agents | Support Agents |
-|-----------|---------------|----------------|
-| Bug Fix | `coder`, `tester` | `reviewer` |
-| New Feature | `architect`, `coder`, `tester` | `researcher`, `reviewer` |
-| Refactoring | `code-analyzer`, `coder` | `tester`, `reviewer` |
-| Performance | `perf-analyzer`, `coder` | `tester` |
-| Security | `security-manager`, `reviewer` | `coder`, `tester` |
-| Documentation | `api-docs`, `researcher` | `reviewer` |
-| Full-Stack | `backend-dev`, `coder`, `tester` | `architect`, `reviewer`, `cicd-engineer` |
-
-### Task Complexity Detection
-
-**Auto-invoke swarm when:**
-- Task involves 3+ files
-- Task is a new feature or module
-- Task requires architectural decisions
-- Task involves multiple concerns (API + DB + UI)
-- User requests "comprehensive" or "full" implementation
-
-**Skip swarm for:**
-- Single file edits
-- Simple bug fixes (1-2 line changes)
-- Documentation updates
-- Configuration changes
-
-### Settings Configuration
-
-Claude Code should ensure proper settings via hooks:
-
-```bash
-# Auto-configure on session start
-npx claude-flow@alpha hooks session-start --auto-configure
-npx claude-flow@alpha memory store --key "session/config" --value '{"topology":"hierarchical-mesh","maxAgents":15}'
-```
-
-### Swarm Lifecycle Management
-
-**Session Start (automatic):**
-```javascript
-[Auto-Init on Complex Task]:
- // Check task complexity
- mcp__claude-flow__features_detect { component: "task-analyzer" }
-
- // Initialize if complex
- mcp__claude-flow__swarm_init { topology: "hierarchical-mesh" }
- mcp__claude-flow__memory_usage { action: "store", key: "session/active", value: "true" }
-
- // Spawn initial agents
- Task("Coordinator", "Manage swarm coordination...", "hierarchical-coordinator")
-```
-
-**Task Execution (automatic):**
-```javascript
-[During Task - Memory Coordination]:
- // Store decisions in shared memory
- mcp__claude-flow__memory_usage { action: "store", key: "task/decisions", value: "[decisions]" }
-
- // Track progress
- mcp__claude-flow__task_status { taskId: "[current-task]" }
-
- // Neural learning from patterns
- mcp__claude-flow__neural_patterns { action: "learn", operation: "[what was done]", outcome: "[result]" }
-```
-
-**Session End (automatic):**
-```javascript
-[Auto-Cleanup]:
- // Persist learnings
- mcp__claude-flow__memory_persist { sessionId: "[session-id]" }
-
- // Export metrics
- mcp__claude-flow__swarm_status { verbose: true }
-
- // Train neural patterns
- mcp__claude-flow__neural_train { pattern_type: "coordination", training_data: "[session-summary]" }
-```
-
-## πŸš€ Quick Setup
-
-```bash
-# Add MCP servers (Claude Flow required, others optional)
-claude mcp add claude-flow npx claude-flow@alpha mcp start
-claude mcp add ruv-swarm npx ruv-swarm mcp start # Optional: Enhanced coordination
-claude mcp add flow-nexus npx flow-nexus@latest mcp start # Optional: Cloud features
-```
-
-## MCP Tool Categories
-
-### Coordination
-`swarm_init`, `agent_spawn`, `task_orchestrate`
-
-### Monitoring
-`swarm_status`, `agent_list`, `agent_metrics`, `task_status`, `task_results`
-
-### Memory & Neural
-`memory_usage`, `neural_status`, `neural_train`, `neural_patterns`
-
-### GitHub Integration
-`github_swarm`, `repo_analyze`, `pr_enhance`, `issue_triage`, `code_review`
-
-### System
-`benchmark_run`, `features_detect`, `swarm_monitor`
-
-### Flow-Nexus MCP Tools (Optional Advanced Features)
-Flow-Nexus extends MCP capabilities with 70+ cloud-based orchestration tools:
-
-**Key MCP Tool Categories:**
-- **Swarm & Agents**: `swarm_init`, `swarm_scale`, `agent_spawn`, `task_orchestrate`
-- **Sandboxes**: `sandbox_create`, `sandbox_execute`, `sandbox_upload` (cloud execution)
-- **Templates**: `template_list`, `template_deploy` (pre-built project templates)
-- **Neural AI**: `neural_train`, `neural_patterns`, `seraphina_chat` (AI assistant)
-- **GitHub**: `github_repo_analyze`, `github_pr_manage` (repository management)
-- **Real-time**: `execution_stream_subscribe`, `realtime_subscribe` (live monitoring)
-- **Storage**: `storage_upload`, `storage_list` (cloud file management)
-
-**Authentication Required:**
-- Register: `mcp__flow-nexus__user_register` or `npx flow-nexus@latest register`
-- Login: `mcp__flow-nexus__user_login` or `npx flow-nexus@latest login`
-- Access 70+ specialized MCP tools for advanced orchestration
-
-## πŸš€ Agent Execution Flow with Claude Code
-
-### The Correct Pattern:
-
-1. **Optional**: Use MCP tools to set up coordination topology
-2. **REQUIRED**: Use Claude Code's Task tool to spawn agents that do actual work
-3. **REQUIRED**: Each agent runs hooks for coordination
-4. **REQUIRED**: Batch all operations in single messages
-
-### Example Full-Stack Development:
-
-```javascript
-// Single message with all agent spawning via Claude Code's Task tool
-[Parallel Agent Execution]:
- Task("Backend Developer", "Build REST API with Express. Use hooks for coordination.", "backend-dev")
- Task("Frontend Developer", "Create React UI. Coordinate with backend via memory.", "coder")
- Task("Database Architect", "Design PostgreSQL schema. Store schema in memory.", "code-analyzer")
- Task("Test Engineer", "Write Jest tests. Check memory for API contracts.", "tester")
- Task("DevOps Engineer", "Setup Docker and CI/CD. Document in memory.", "cicd-engineer")
- Task("Security Auditor", "Review authentication. Report findings via hooks.", "reviewer")
-
- // All todos batched together
- TodoWrite { todos: [...8-10 todos...] }
-
- // All file operations together
- Write "backend/server.js"
- Write "frontend/App.jsx"
- Write "database/schema.sql"
-```
-
-## πŸ“‹ Agent Coordination Protocol
-
-### Every Agent Spawned via Task Tool MUST:
-
-**1️⃣ BEFORE Work:**
-```bash
-npx claude-flow@alpha hooks pre-task --description "[task]"
-npx claude-flow@alpha hooks session-restore --session-id "swarm-[id]"
-```
-
-**2️⃣ DURING Work:**
-```bash
-npx claude-flow@alpha hooks post-edit --file "[file]" --memory-key "swarm/[agent]/[step]"
-npx claude-flow@alpha hooks notify --message "[what was done]"
-```
-
-**3️⃣ AFTER Work:**
-```bash
-npx claude-flow@alpha hooks post-task --task-id "[task]"
-npx claude-flow@alpha hooks session-end --export-metrics true
-```
-
-## 🎯 Concurrent Execution Examples
-
-### βœ… CORRECT WORKFLOW: MCP Coordinates, Claude Code Executes
-
-```javascript
-// Step 1: MCP tools set up coordination (optional, for complex tasks)
-[Single Message - Coordination Setup]:
- mcp__claude-flow__swarm_init { topology: "mesh", maxAgents: 6 }
- mcp__claude-flow__agent_spawn { type: "researcher" }
- mcp__claude-flow__agent_spawn { type: "coder" }
- mcp__claude-flow__agent_spawn { type: "tester" }
-
-// Step 2: Claude Code Task tool spawns ACTUAL agents that do the work
-[Single Message - Parallel Agent Execution]:
- // Claude Code's Task tool spawns real agents concurrently
- Task("Research agent", "Analyze API requirements and best practices. Check memory for prior decisions.", "researcher")
- Task("Coder agent", "Implement REST endpoints with authentication. Coordinate via hooks.", "coder")
- Task("Database agent", "Design and implement database schema. Store decisions in memory.", "code-analyzer")
- Task("Tester agent", "Create comprehensive test suite with 90% coverage.", "tester")
- Task("Reviewer agent", "Review code quality and security. Document findings.", "reviewer")
-
- // Batch ALL todos in ONE call
- TodoWrite { todos: [
- {id: "1", content: "Research API patterns", status: "in_progress", priority: "high"},
- {id: "2", content: "Design database schema", status: "in_progress", priority: "high"},
- {id: "3", content: "Implement authentication", status: "pending", priority: "high"},
- {id: "4", content: "Build REST endpoints", status: "pending", priority: "high"},
- {id: "5", content: "Write unit tests", status: "pending", priority: "medium"},
- {id: "6", content: "Integration tests", status: "pending", priority: "medium"},
- {id: "7", content: "API documentation", status: "pending", priority: "low"},
- {id: "8", content: "Performance optimization", status: "pending", priority: "low"}
- ]}
-
- // Parallel file operations
- Bash "mkdir -p app/{src,tests,docs,config}"
- Write "app/package.json"
- Write "app/src/server.js"
- Write "app/tests/server.test.js"
- Write "app/docs/API.md"
-```
-
-### ❌ WRONG (Multiple Messages):
-```javascript
-Message 1: mcp__claude-flow__swarm_init
-Message 2: Task("agent 1")
-Message 3: TodoWrite { todos: [single todo] }
-Message 4: Write "file.js"
-// This breaks parallel coordination!
-```
-
-## Performance Benefits
-
-- **84.8% SWE-Bench solve rate**
-- **32.3% token reduction**
-- **2.8-4.4x speed improvement**
-- **27+ neural models**
-
-## πŸͺ V3 Hooks System (26 Hooks)
-
-Claude Flow V3 provides 26 hooks for comprehensive agent coordination and self-learning.
+## πŸͺ V3 Hooks System (17 Hooks + 12 Workers)
### Hook Categories
| Category | Hooks | Purpose |
|----------|-------|---------|
| **Core** | `pre-edit`, `post-edit`, `pre-command`, `post-command`, `pre-task`, `post-task` | Tool lifecycle |
-| **Routing** | `route`, `metrics`, `list` | Task analysis |
-| **Intelligence** | `explain`, `pretrain`, `build-agents`, `transfer`, `init` | Neural learning |
| **Session** | `session-start`, `session-end`, `session-restore`, `notify` | Context management |
-| **Learning** | `trajectory-start`, `trajectory-step`, `trajectory-end` | Reinforcement learning |
-| **Patterns** | `pattern-store`, `pattern-search`, `stats`, `learn`, `attention` | Memory & search |
+| **Intelligence** | `route`, `explain`, `pretrain`, `build-agents`, `transfer` | Neural learning |
+| **Learning** | `intelligence` (trajectory-start/step/end, pattern-store/search, stats, attention) | Reinforcement |
+
+### 12 Background Workers
+
+| Worker | Priority | Description |
+|--------|----------|-------------|
+| `ultralearn` | normal | Deep knowledge acquisition |
+| `optimize` | high | Performance optimization |
+| `consolidate` | low | Memory consolidation |
+| `predict` | normal | Predictive preloading |
+| `audit` | critical | Security analysis |
+| `map` | normal | Codebase mapping |
+| `preload` | low | Resource preloading |
+| `deepdive` | normal | Deep code analysis |
+| `document` | normal | Auto-documentation |
+| `refactor` | normal | Refactoring suggestions |
+| `benchmark` | normal | Performance benchmarking |
+| `testgaps` | normal | Test coverage analysis |
### Essential Hook Commands
```bash
-# Core hooks for tool coordination
-npx claude-flow@alpha hooks pre-task --description "[task]"
-npx claude-flow@alpha hooks post-task --task-id "[id]" --success true
-npx claude-flow@alpha hooks post-edit --file "[file]" --train-patterns
+# Core hooks
+npx claude-flow@v3alpha hooks pre-task --description "[task]"
+npx claude-flow@v3alpha hooks post-task --task-id "[id]" --success true
+npx claude-flow@v3alpha hooks post-edit --file "[file]" --train-patterns
# Session management
-npx claude-flow@alpha hooks session-start --session-id "[id]"
-npx claude-flow@alpha hooks session-end --export-metrics true --persist-patterns
-npx claude-flow@alpha hooks session-restore --session-id "[id]"
+npx claude-flow@v3alpha hooks session-start --session-id "[id]"
+npx claude-flow@v3alpha hooks session-end --export-metrics true
+npx claude-flow@v3alpha hooks session-restore --session-id "[id]"
# Intelligence routing
-npx claude-flow@alpha hooks route --task "[task]" --include-explanation
-npx claude-flow@alpha hooks explain --topic "[topic]" --depth comprehensive
-
-# Neural learning (RuVector Intelligence)
-npx claude-flow@alpha hooks pretrain --model-type moe --epochs 10
-npx claude-flow@alpha hooks build-agents --agent-types coder,tester --config-format yaml
-
-# Trajectory learning (reinforcement)
-npx claude-flow@alpha hooks intelligence trajectory-start --session "[session]"
-npx claude-flow@alpha hooks intelligence trajectory-step --action "[action]" --reward "[reward]"
-npx claude-flow@alpha hooks intelligence trajectory-end --verdict success
+npx claude-flow@v3alpha hooks route --task "[task]"
+npx claude-flow@v3alpha hooks explain --topic "[topic]"
-# Pattern storage (HNSW-indexed, 150x faster)
-npx claude-flow@alpha hooks intelligence pattern-store --pattern "[pattern]" --embedding "[json]"
-npx claude-flow@alpha hooks intelligence pattern-search --query "[query]" --limit 10
+# Neural learning
+npx claude-flow@v3alpha hooks pretrain --model-type moe --epochs 10
+npx claude-flow@v3alpha hooks build-agents --agent-types coder,tester
-# Learning stats & attention
-npx claude-flow@alpha hooks intelligence stats
-npx claude-flow@alpha hooks intelligence attention --focus "[task]"
+# Background workers
+npx claude-flow@v3alpha hooks worker list
+npx claude-flow@v3alpha hooks worker dispatch --trigger audit
+npx claude-flow@v3alpha hooks worker status
```
-### Intelligence System (RuVector)
+## 🧠 Intelligence System (RuVector)
-V3 includes the RuVector Intelligence System with:
-- **SONA**: Self-Optimizing Neural Architecture
+V3 includes the RuVector Intelligence System:
+- **SONA**: Self-Optimizing Neural Architecture (<0.05ms adaptation)
- **MoE**: Mixture of Experts for specialized routing
-- **HNSW**: 150x faster pattern search (vs brute force)
-- **EWC++**: Elastic Weight Consolidation (prevents catastrophic forgetting)
+- **HNSW**: 150x-12,500x faster pattern search
+- **EWC++**: Elastic Weight Consolidation (prevents forgetting)
- **Flash Attention**: 2.49x-7.47x speedup
The 4-step intelligence pipeline:
-1. **RETRIEVE** - Fetch relevant patterns via HNSW indexing
-2. **JUDGE** - Evaluate with verdicts (success/failure/partial)
-3. **DISTILL** - Extract key learnings via LoRA fine-tuning
-4. **CONSOLIDATE** - Prevent forgetting via EWC++
+1. **RETRIEVE** - Fetch relevant patterns via HNSW
+2. **JUDGE** - Evaluate with verdicts (success/failure)
+3. **DISTILL** - Extract key learnings via LoRA
+4. **CONSOLIDATE** - Prevent catastrophic forgetting via EWC++
+
+## πŸ“¦ Embeddings Package (v3.0.0-alpha.12)
+
+Features:
+- **sql.js**: Cross-platform SQLite persistent cache (WASM, no native compilation)
+- **Document chunking**: Configurable overlap and size
+- **Normalization**: L2, L1, min-max, z-score
+- **Hyperbolic embeddings**: PoincarΓ© ball model for hierarchical data
+- **75x faster**: With agentic-flow ONNX integration
+- **Neural substrate**: Integration with RuVector
+
+## 🐝 Hive-Mind Consensus
+
+### Topologies
+- `hierarchical` - Queen controls workers directly
+- `mesh` - Fully connected peer network
+- `hierarchical-mesh` - Hybrid (recommended)
+- `adaptive` - Dynamic based on load
+
+### Consensus Strategies
+- `byzantine` - BFT (tolerates f < n/3 faulty)
+- `raft` - Leader-based (tolerates f < n/2)
+- `gossip` - Epidemic for eventual consistency
+- `crdt` - Conflict-free replicated data types
+- `quorum` - Configurable quorum-based
+
+## V3 Performance Targets
+
+| Metric | Target |
+|--------|--------|
+| Flash Attention | 2.49x-7.47x speedup |
+| HNSW Search | 150x-12,500x faster |
+| Memory Reduction | 50-75% with quantization |
+| MCP Response | <100ms |
+| CLI Startup | <500ms |
+| SONA Adaptation | <0.05ms |
+
+## πŸ”§ Environment Variables
+
+```bash
+# Configuration
+CLAUDE_FLOW_CONFIG=./claude-flow.config.json
+CLAUDE_FLOW_LOG_LEVEL=info
+
+# Provider API Keys
+ANTHROPIC_API_KEY=sk-ant-...
+OPENAI_API_KEY=sk-...
+GOOGLE_API_KEY=...
+
+# MCP Server
+CLAUDE_FLOW_MCP_PORT=3000
+CLAUDE_FLOW_MCP_HOST=localhost
+CLAUDE_FLOW_MCP_TRANSPORT=stdio
+
+# Memory
+CLAUDE_FLOW_MEMORY_BACKEND=hybrid
+CLAUDE_FLOW_MEMORY_PATH=./data/memory
+```
-### Agent Coordination Protocol
+## πŸ” Doctor Health Checks
-Every agent spawned via Task tool should use hooks:
+Run `npx claude-flow@v3alpha doctor` to check:
+- Node.js version (20+)
+- npm version (9+)
+- Git installation
+- Config file validity
+- Daemon status
+- Memory database
+- API keys
+- MCP servers
+- Disk space
+- TypeScript installation
-```javascript
-// In agent prompt instructions
-Task("Coder", `
- BEFORE starting: npx claude-flow@alpha hooks pre-task --description "Implement feature X"
+## πŸš€ Quick Setup
- DURING work:
- - After each file edit: npx claude-flow@alpha hooks post-edit --file "[file]"
- - To notify others: npx claude-flow@alpha hooks notify --message "[update]"
+```bash
+# Add MCP servers
+claude mcp add claude-flow npx claude-flow@v3alpha mcp start
+claude mcp add ruv-swarm npx ruv-swarm mcp start # Optional
+claude mcp add flow-nexus npx flow-nexus@latest mcp start # Optional
+
+# Start daemon
+npx claude-flow@v3alpha daemon start
- AFTER completing: npx claude-flow@alpha hooks post-task --success true
-`, "coder")
+# Run doctor
+npx claude-flow@v3alpha doctor --fix
```
-### Hooks Integration
-
-#### Pre-Operation
-- Auto-assign agents by file type
-- Validate commands for safety
-- Prepare resources automatically
-- Optimize topology by complexity
-- Cache searches
-
-#### Post-Operation
-- Auto-format code
-- Train neural patterns
-- Update memory
-- Analyze performance
-- Track token usage
-
-#### Session Management
-- Generate summaries
-- Persist state
-- Track metrics
-- Restore context
-- Export workflows
-
-## Advanced Features (v2.0.0)
-
-- πŸš€ Automatic Topology Selection
-- ⚑ Parallel Execution (2.8-4.4x speed)
-- 🧠 Neural Training
-- πŸ“Š Bottleneck Analysis
-- πŸ€– Smart Auto-Spawning
-- πŸ›‘οΈ Self-Healing Workflows
-- πŸ’Ύ Cross-Session Memory
-- πŸ”— GitHub Integration
-
-## Integration Tips
-
-1. Start with basic swarm init
-2. Scale agents gradually
-3. Use memory for context
-4. Monitor progress regularly
-5. Train patterns from success
-6. Enable hooks automation
-7. Use GitHub tools first
+## 🎯 Claude Code vs MCP Tools
+
+### Claude Code Handles ALL EXECUTION:
+- **Task tool**: Spawn and run agents concurrently
+- File operations (Read, Write, Edit, MultiEdit, Glob, Grep)
+- Code generation and programming
+- Bash commands and system operations
+- TodoWrite and task management
+- Git operations
+
+### MCP Tools ONLY COORDINATE:
+- Swarm initialization (topology setup)
+- Agent type definitions
+- Task orchestration
+- Memory management
+- Neural features
+- Performance tracking
+
+**KEY**: MCP coordinates the strategy, Claude Code's Task tool executes with real agents.
## Support
- Documentation: https://github.com/ruvnet/claude-flow
- Issues: https://github.com/ruvnet/claude-flow/issues
-- Flow-Nexus Platform: https://flow-nexus.ruv.io (registration required for cloud features)
---
@@ -573,3 +410,4 @@ NEVER create files unless they're absolutely necessary for achieving your goal.
ALWAYS prefer editing an existing file to creating a new one.
NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
Never save working files, text/mds and tests to the root folder.
+After spawning a swarm, wait, don't continuously check status.
diff --git a/agents/architect.yaml b/agents/architect.yaml
index c6c8c8cb14..5a50500b35 100644
--- a/agents/architect.yaml
+++ b/agents/architect.yaml
@@ -8,4 +8,4 @@ capabilities:
optimizations:
- context-caching
- memory-persistence
-createdAt: "2026-01-07T05:11:07.545Z"
+createdAt: "2026-01-07T05:24:54.951Z"
diff --git a/agents/coder.yaml b/agents/coder.yaml
index 5082c9fdb8..39c460479f 100644
--- a/agents/coder.yaml
+++ b/agents/coder.yaml
@@ -8,4 +8,4 @@ capabilities:
optimizations:
- flash-attention
- token-reduction
-createdAt: "2026-01-07T05:11:07.544Z"
+createdAt: "2026-01-07T05:24:54.951Z"
diff --git a/agents/reviewer.yaml b/agents/reviewer.yaml
index d1d6615866..0957537b32 100644
--- a/agents/reviewer.yaml
+++ b/agents/reviewer.yaml
@@ -7,4 +7,4 @@ capabilities:
- best-practices
optimizations:
- incremental-analysis
-createdAt: "2026-01-07T05:11:07.545Z"
+createdAt: "2026-01-07T05:24:54.951Z"
diff --git a/agents/security-architect.yaml b/agents/security-architect.yaml
index 5ff811112d..3ba9b187ef 100644
--- a/agents/security-architect.yaml
+++ b/agents/security-architect.yaml
@@ -7,4 +7,4 @@ capabilities:
- security-review
optimizations:
- pattern-matching
-createdAt: "2026-01-07T05:11:07.545Z"
+createdAt: "2026-01-07T05:24:54.951Z"
diff --git a/agents/tester.yaml b/agents/tester.yaml
index 87720f250c..9d9e312516 100644
--- a/agents/tester.yaml
+++ b/agents/tester.yaml
@@ -7,4 +7,4 @@ capabilities:
- coverage
optimizations:
- parallel-execution
-createdAt: "2026-01-07T05:11:07.545Z"
+createdAt: "2026-01-07T05:24:54.951Z"
diff --git a/v3/@claude-flow/cli/src/commands/analyze.ts b/v3/@claude-flow/cli/src/commands/analyze.ts
index 7fc15a327c..4add75fc88 100644
--- a/v3/@claude-flow/cli/src/commands/analyze.ts
+++ b/v3/@claude-flow/cli/src/commands/analyze.ts
@@ -336,44 +336,1652 @@ const codeCommand: Command = {
},
};
+// ============================================================================
+// AST Analysis Subcommands (using ruvector tree-sitter with fallback)
+// ============================================================================
+
+/**
+ * Helper: Truncate file path for display
+ */
+function truncatePathAst(filePath: string, maxLen: number = 45): string {
+ if (filePath.length <= maxLen) return filePath;
+ return '...' + filePath.slice(-(maxLen - 3));
+}
+
+/**
+ * Helper: Format complexity value with color coding
+ */
+function formatComplexityValueAst(value: number): string {
+ if (value <= 5) return output.success(String(value));
+ if (value <= 10) return output.warning(String(value));
+ return output.error(String(value));
+}
+
+/**
+ * Helper: Get type marker for symbols
+ */
+function getTypeMarkerAst(type: string): string {
+ switch (type) {
+ case 'function': return output.success('fn');
+ case 'class': return output.info('class');
+ case 'variable': return output.dim('var');
+ case 'type': return output.highlight('type');
+ case 'interface': return output.highlight('iface');
+ default: return output.dim(type.slice(0, 5));
+ }
+}
+
+/**
+ * Helper: Get complexity rating text
+ */
+function getComplexityRatingAst(value: number): string {
+ if (value <= 5) return output.success('Simple');
+ if (value <= 10) return output.warning('Moderate');
+ if (value <= 20) return output.error('Complex');
+ return output.error(output.bold('Very Complex'));
+}
+
+/**
+ * AST analysis subcommand
+ */
+const astCommand: Command = {
+ name: 'ast',
+ description: 'Analyze code using AST parsing (tree-sitter via ruvector)',
+ options: [
+ {
+ name: 'complexity',
+ short: 'c',
+ description: 'Include complexity metrics',
+ type: 'boolean',
+ default: false,
+ },
+ {
+ name: 'symbols',
+ short: 's',
+ description: 'Include symbol extraction',
+ type: 'boolean',
+ default: false,
+ },
+ {
+ name: 'format',
+ short: 'f',
+ description: 'Output format (text, json, table)',
+ type: 'string',
+ default: 'text',
+ choices: ['text', 'json', 'table'],
+ },
+ {
+ name: 'output',
+ short: 'o',
+ description: 'Output file path',
+ type: 'string',
+ },
+ {
+ name: 'verbose',
+ short: 'v',
+ description: 'Show detailed analysis',
+ type: 'boolean',
+ default: false,
+ },
+ ],
+ examples: [
+ { command: 'claude-flow analyze ast src/', description: 'Analyze all files in src/' },
+ { command: 'claude-flow analyze ast src/index.ts --complexity', description: 'Analyze with complexity' },
+ { command: 'claude-flow analyze ast . --format json', description: 'JSON output' },
+ { command: 'claude-flow analyze ast src/ --symbols', description: 'Extract symbols' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const targetPath = ctx.args[0] || ctx.cwd;
+ const showComplexity = ctx.flags.complexity as boolean;
+ const showSymbols = ctx.flags.symbols as boolean;
+ const formatType = (ctx.flags.format as string) || 'text';
+ const outputFile = ctx.flags.output as string | undefined;
+ const verbose = ctx.flags.verbose as boolean;
+
+ // If no specific flags, show summary
+ const showAll = !showComplexity && !showSymbols;
+
+ output.printInfo(`Analyzing: ${output.highlight(targetPath)}`);
+ output.writeln();
+
+ const spinner = output.createSpinner({ text: 'Parsing AST...', spinner: 'dots' });
+ spinner.start();
+
+ try {
+ const astModule = await getASTAnalyzer();
+ if (!astModule) {
+ spinner.stop();
+ output.printWarning('AST analyzer not available, using regex fallback');
+ }
+
+ // Resolve path and check if file or directory
+ const resolvedPath = resolve(targetPath);
+ const stat = await fs.stat(resolvedPath);
+ const isDirectory = stat.isDirectory();
+
+ let results: Array<{
+ filePath: string;
+ language: string;
+ functions: Array<{ name: string; startLine: number; endLine: number }>;
+ classes: Array<{ name: string; startLine: number; endLine: number }>;
+ imports: string[];
+ exports: string[];
+ complexity: { cyclomatic: number; cognitive: number; loc: number; commentDensity: number };
+ }> = [];
+
+ if (isDirectory) {
+ // Scan directory for source files
+ const files = await scanSourceFiles(resolvedPath);
+ spinner.stop();
+ output.printInfo(`Found ${files.length} source files`);
+ spinner.start();
+
+ for (const file of files.slice(0, 100)) {
+ try {
+ const content = await fs.readFile(file, 'utf-8');
+ if (astModule) {
+ const analyzer = astModule.createASTAnalyzer();
+ const analysis = analyzer.analyze(content, file);
+ results.push(analysis);
+ } else {
+ // Fallback analysis
+ results.push(fallbackAnalyze(content, file));
+ }
+ } catch {
+ // Skip files that can't be analyzed
+ }
+ }
+ } else {
+ // Single file
+ const content = await fs.readFile(resolvedPath, 'utf-8');
+ if (astModule) {
+ const analyzer = astModule.createASTAnalyzer();
+ const analysis = analyzer.analyze(content, resolvedPath);
+ results.push(analysis);
+ } else {
+ results.push(fallbackAnalyze(content, resolvedPath));
+ }
+ }
+
+ spinner.stop();
+
+ if (results.length === 0) {
+ output.printWarning('No files analyzed');
+ return { success: true };
+ }
+
+ // Calculate totals
+ const totals = {
+ files: results.length,
+ functions: results.reduce((sum, r) => sum + r.functions.length, 0),
+ classes: results.reduce((sum, r) => sum + r.classes.length, 0),
+ imports: results.reduce((sum, r) => sum + r.imports.length, 0),
+ avgComplexity: results.reduce((sum, r) => sum + r.complexity.cyclomatic, 0) / results.length,
+ totalLoc: results.reduce((sum, r) => sum + r.complexity.loc, 0),
+ };
+
+ // JSON output
+ if (formatType === 'json') {
+ const jsonOutput = { files: results, totals };
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ } else {
+ output.printJson(jsonOutput);
+ }
+ return { success: true, data: jsonOutput };
+ }
+
+ // Summary box
+ output.printBox(
+ [
+ `Files analyzed: ${totals.files}`,
+ `Functions: ${totals.functions}`,
+ `Classes: ${totals.classes}`,
+ `Total LOC: ${totals.totalLoc}`,
+ `Avg Complexity: ${formatComplexityValueAst(Math.round(totals.avgComplexity))}`,
+ ].join('\n'),
+ 'AST Analysis Summary'
+ );
+
+ // Complexity view
+ if (showComplexity || showAll) {
+ output.writeln();
+ output.writeln(output.bold('Complexity by File'));
+ output.writeln(output.dim('-'.repeat(60)));
+
+ const complexityData = results
+ .map(r => ({
+ file: truncatePathAst(r.filePath),
+ cyclomatic: r.complexity.cyclomatic,
+ cognitive: r.complexity.cognitive,
+ loc: r.complexity.loc,
+ rating: getComplexityRatingAst(r.complexity.cyclomatic),
+ }))
+ .sort((a, b) => b.cyclomatic - a.cyclomatic)
+ .slice(0, 15);
+
+ output.printTable({
+ columns: [
+ { key: 'file', header: 'File', width: 40 },
+ { key: 'cyclomatic', header: 'Cyclo', width: 8, align: 'right', format: (v) => formatComplexityValueAst(v as number) },
+ { key: 'cognitive', header: 'Cogni', width: 8, align: 'right' },
+ { key: 'loc', header: 'LOC', width: 8, align: 'right' },
+ { key: 'rating', header: 'Rating', width: 15 },
+ ],
+ data: complexityData,
+ });
+
+ if (results.length > 15) {
+ output.writeln(output.dim(` ... and ${results.length - 15} more files`));
+ }
+ }
+
+ // Symbols view
+ if (showSymbols || showAll) {
+ output.writeln();
+ output.writeln(output.bold('Extracted Symbols'));
+ output.writeln(output.dim('-'.repeat(60)));
+
+ const allSymbols: Array<{ name: string; type: string; file: string; line: number }> = [];
+
+ for (const r of results) {
+ for (const fn of r.functions) {
+ allSymbols.push({ name: fn.name, type: 'function', file: truncatePathAst(r.filePath, 30), line: fn.startLine });
+ }
+ for (const cls of r.classes) {
+ allSymbols.push({ name: cls.name, type: 'class', file: truncatePathAst(r.filePath, 30), line: cls.startLine });
+ }
+ }
+
+ const displaySymbols = allSymbols.slice(0, 20);
+
+ output.printTable({
+ columns: [
+ { key: 'type', header: 'Type', width: 8, format: (v) => getTypeMarkerAst(v as string) },
+ { key: 'name', header: 'Symbol', width: 30 },
+ { key: 'file', header: 'File', width: 35 },
+ { key: 'line', header: 'Line', width: 8, align: 'right' },
+ ],
+ data: displaySymbols,
+ });
+
+ if (allSymbols.length > 20) {
+ output.writeln(output.dim(` ... and ${allSymbols.length - 20} more symbols`));
+ }
+ }
+
+ // Verbose output
+ if (verbose) {
+ output.writeln();
+ output.writeln(output.bold('Import Analysis'));
+ output.writeln(output.dim('-'.repeat(60)));
+
+ const importCounts: Map<string, number> = new Map();
+ for (const r of results) {
+ for (const imp of r.imports) {
+ importCounts.set(imp, (importCounts.get(imp) || 0) + 1);
+ }
+ }
+
+ const topImports = Array.from(importCounts.entries())
+ .sort((a, b) => b[1] - a[1])
+ .slice(0, 10);
+
+ for (const [imp, count] of topImports) {
+ output.writeln(` ${output.highlight(count.toString().padStart(3))} ${imp}`);
+ }
+ }
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify({ files: results, totals }, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ }
+
+ return { success: true, data: { files: results, totals } };
+ } catch (error) {
+ spinner.stop();
+ const message = error instanceof Error ? error.message : String(error);
+ output.printError(`AST analysis failed: ${message}`);
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+/**
+ * Complexity analysis subcommand
+ */
+const complexityAstCommand: Command = {
+ name: 'complexity',
+ aliases: ['cx'],
+ description: 'Analyze code complexity metrics',
+ options: [
+ {
+ name: 'threshold',
+ short: 't',
+ description: 'Complexity threshold to flag (default: 10)',
+ type: 'number',
+ default: 10,
+ },
+ {
+ name: 'format',
+ short: 'f',
+ description: 'Output format (text, json)',
+ type: 'string',
+ default: 'text',
+ choices: ['text', 'json'],
+ },
+ {
+ name: 'output',
+ short: 'o',
+ description: 'Output file path',
+ type: 'string',
+ },
+ ],
+ examples: [
+ { command: 'claude-flow analyze complexity src/', description: 'Analyze complexity' },
+ { command: 'claude-flow analyze complexity src/ --threshold 15', description: 'Flag high complexity' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const targetPath = ctx.args[0] || ctx.cwd;
+ const threshold = (ctx.flags.threshold as number) || 10;
+ const formatType = (ctx.flags.format as string) || 'text';
+ const outputFile = ctx.flags.output as string | undefined;
+
+ output.printInfo(`Analyzing complexity: ${output.highlight(targetPath)}`);
+ output.writeln();
+
+ const spinner = output.createSpinner({ text: 'Calculating complexity...', spinner: 'dots' });
+ spinner.start();
+
+ try {
+ const astModule = await getASTAnalyzer();
+ const resolvedPath = resolve(targetPath);
+ const stat = await fs.stat(resolvedPath);
+ const files = stat.isDirectory() ? await scanSourceFiles(resolvedPath) : [resolvedPath];
+
+ const results: Array<{
+ file: string;
+ cyclomatic: number;
+ cognitive: number;
+ loc: number;
+ commentDensity: number;
+ rating: string;
+ flagged: boolean;
+ }> = [];
+
+ for (const file of files.slice(0, 100)) {
+ try {
+ const content = await fs.readFile(file, 'utf-8');
+ let analysis;
+
+ if (astModule) {
+ const analyzer = astModule.createASTAnalyzer();
+ analysis = analyzer.analyze(content, file);
+ } else {
+ analysis = fallbackAnalyze(content, file);
+ }
+
+ const flagged = analysis.complexity.cyclomatic > threshold;
+ const rating = analysis.complexity.cyclomatic <= 5 ? 'Simple' :
+ analysis.complexity.cyclomatic <= 10 ? 'Moderate' :
+ analysis.complexity.cyclomatic <= 20 ? 'Complex' : 'Very Complex';
+
+ results.push({
+ file: file,
+ cyclomatic: analysis.complexity.cyclomatic,
+ cognitive: analysis.complexity.cognitive,
+ loc: analysis.complexity.loc,
+ commentDensity: analysis.complexity.commentDensity,
+ rating,
+ flagged,
+ });
+ } catch {
+ // Skip files that can't be analyzed
+ }
+ }
+
+ spinner.stop();
+
+ // Sort by complexity descending
+ results.sort((a, b) => b.cyclomatic - a.cyclomatic);
+
+ const flaggedCount = results.filter(r => r.flagged).length;
+ const avgComplexity = results.length > 0
+ ? results.reduce((sum, r) => sum + r.cyclomatic, 0) / results.length
+ : 0;
+
+ if (formatType === 'json') {
+ const jsonOutput = { files: results, summary: { total: results.length, flagged: flaggedCount, avgComplexity, threshold } };
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ } else {
+ output.printJson(jsonOutput);
+ }
+ return { success: true, data: jsonOutput };
+ }
+
+ // Summary
+ output.printBox(
+ [
+ `Files analyzed: ${results.length}`,
+ `Threshold: ${threshold}`,
+ `Flagged files: ${flaggedCount > 0 ? output.error(String(flaggedCount)) : output.success('0')}`,
+ `Average complexity: ${formatComplexityValueAst(Math.round(avgComplexity))}`,
+ ].join('\n'),
+ 'Complexity Analysis'
+ );
+
+ // Show flagged files first
+ if (flaggedCount > 0) {
+ output.writeln();
+ output.writeln(output.bold(output.warning(`High Complexity Files (>${threshold})`)));
+ output.writeln(output.dim('-'.repeat(60)));
+
+ const flaggedFiles = results.filter(r => r.flagged).slice(0, 10);
+ output.printTable({
+ columns: [
+ { key: 'file', header: 'File', width: 40, format: (v) => truncatePathAst(v as string) },
+ { key: 'cyclomatic', header: 'Cyclo', width: 8, align: 'right', format: (v) => output.error(String(v)) },
+ { key: 'cognitive', header: 'Cogni', width: 8, align: 'right' },
+ { key: 'loc', header: 'LOC', width: 8, align: 'right' },
+ { key: 'rating', header: 'Rating', width: 15 },
+ ],
+ data: flaggedFiles,
+ });
+ }
+
+ // Show all files in table format
+ output.writeln();
+ output.writeln(output.bold('All Files'));
+ output.writeln(output.dim('-'.repeat(60)));
+
+ const displayFiles = results.slice(0, 15);
+ output.printTable({
+ columns: [
+ { key: 'file', header: 'File', width: 40, format: (v) => truncatePathAst(v as string) },
+ { key: 'cyclomatic', header: 'Cyclo', width: 8, align: 'right', format: (v) => formatComplexityValueAst(v as number) },
+ { key: 'cognitive', header: 'Cogni', width: 8, align: 'right' },
+ { key: 'loc', header: 'LOC', width: 8, align: 'right' },
+ ],
+ data: displayFiles,
+ });
+
+ if (results.length > 15) {
+ output.writeln(output.dim(` ... and ${results.length - 15} more files`));
+ }
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify({ files: results, summary: { total: results.length, flagged: flaggedCount, avgComplexity, threshold } }, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ }
+
+ return { success: true, data: { files: results, flaggedCount } };
+ } catch (error) {
+ spinner.stop();
+ const message = error instanceof Error ? error.message : String(error);
+ output.printError(`Complexity analysis failed: ${message}`);
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+/**
+ * Symbol extraction subcommand
+ */
+const symbolsCommand: Command = {
+ name: 'symbols',
+ aliases: ['sym'],
+ description: 'Extract and list code symbols (functions, classes, types)',
+ options: [
+ {
+ name: 'type',
+ short: 't',
+ description: 'Filter by symbol type (function, class, all)',
+ type: 'string',
+ default: 'all',
+ choices: ['function', 'class', 'all'],
+ },
+ {
+ name: 'format',
+ short: 'f',
+ description: 'Output format (text, json)',
+ type: 'string',
+ default: 'text',
+ choices: ['text', 'json'],
+ },
+ {
+ name: 'output',
+ short: 'o',
+ description: 'Output file path',
+ type: 'string',
+ },
+ ],
+ examples: [
+ { command: 'claude-flow analyze symbols src/', description: 'Extract all symbols' },
+ { command: 'claude-flow analyze symbols src/ --type function', description: 'Only functions' },
+ { command: 'claude-flow analyze symbols src/ --format json', description: 'JSON output' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const targetPath = ctx.args[0] || ctx.cwd;
+ const symbolType = (ctx.flags.type as string) || 'all';
+ const formatType = (ctx.flags.format as string) || 'text';
+ const outputFile = ctx.flags.output as string | undefined;
+
+ output.printInfo(`Extracting symbols: ${output.highlight(targetPath)}`);
+ output.writeln();
+
+ const spinner = output.createSpinner({ text: 'Parsing code...', spinner: 'dots' });
+ spinner.start();
+
+ try {
+ const astModule = await getASTAnalyzer();
+ const resolvedPath = resolve(targetPath);
+ const stat = await fs.stat(resolvedPath);
+ const files = stat.isDirectory() ? await scanSourceFiles(resolvedPath) : [resolvedPath];
+
+ const symbols: Array<{
+ name: string;
+ type: string;
+ file: string;
+ startLine: number;
+ endLine: number;
+ }> = [];
+
+ for (const file of files.slice(0, 100)) {
+ try {
+ const content = await fs.readFile(file, 'utf-8');
+ let analysis;
+
+ if (astModule) {
+ const analyzer = astModule.createASTAnalyzer();
+ analysis = analyzer.analyze(content, file);
+ } else {
+ analysis = fallbackAnalyze(content, file);
+ }
+
+ if (symbolType === 'all' || symbolType === 'function') {
+ for (const fn of analysis.functions) {
+ symbols.push({
+ name: fn.name,
+ type: 'function',
+ file,
+ startLine: fn.startLine,
+ endLine: fn.endLine,
+ });
+ }
+ }
+
+ if (symbolType === 'all' || symbolType === 'class') {
+ for (const cls of analysis.classes) {
+ symbols.push({
+ name: cls.name,
+ type: 'class',
+ file,
+ startLine: cls.startLine,
+ endLine: cls.endLine,
+ });
+ }
+ }
+ } catch {
+ // Skip files that can't be parsed
+ }
+ }
+
+ spinner.stop();
+
+ // Sort by file then name
+ symbols.sort((a, b) => a.file.localeCompare(b.file) || a.name.localeCompare(b.name));
+
+ if (formatType === 'json') {
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(symbols, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ } else {
+ output.printJson(symbols);
+ }
+ return { success: true, data: symbols };
+ }
+
+ // Summary
+ const functionCount = symbols.filter(s => s.type === 'function').length;
+ const classCount = symbols.filter(s => s.type === 'class').length;
+
+ output.printBox(
+ [
+ `Total symbols: ${symbols.length}`,
+ `Functions: ${functionCount}`,
+ `Classes: ${classCount}`,
+ `Files: ${files.length}`,
+ ].join('\n'),
+ 'Symbol Extraction'
+ );
+
+ output.writeln();
+ output.writeln(output.bold('Symbols'));
+ output.writeln(output.dim('-'.repeat(60)));
+
+ const displaySymbols = symbols.slice(0, 30);
+ output.printTable({
+ columns: [
+ { key: 'type', header: 'Type', width: 10, format: (v) => getTypeMarkerAst(v as string) },
+ { key: 'name', header: 'Name', width: 30 },
+ { key: 'file', header: 'File', width: 35, format: (v) => truncatePathAst(v as string, 33) },
+ { key: 'startLine', header: 'Line', width: 8, align: 'right' },
+ ],
+ data: displaySymbols,
+ });
+
+ if (symbols.length > 30) {
+ output.writeln(output.dim(` ... and ${symbols.length - 30} more symbols`));
+ }
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(symbols, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ }
+
+ return { success: true, data: symbols };
+ } catch (error) {
+ spinner.stop();
+ const message = error instanceof Error ? error.message : String(error);
+ output.printError(`Symbol extraction failed: ${message}`);
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+/**
+ * Imports analysis subcommand
+ */
+const importsCommand: Command = {
+ name: 'imports',
+ aliases: ['imp'],
+ description: 'Analyze import dependencies across files',
+ options: [
+ {
+ name: 'format',
+ short: 'f',
+ description: 'Output format (text, json)',
+ type: 'string',
+ default: 'text',
+ choices: ['text', 'json'],
+ },
+ {
+ name: 'output',
+ short: 'o',
+ description: 'Output file path',
+ type: 'string',
+ },
+ {
+ name: 'external',
+ short: 'e',
+ description: 'Show only external (npm) imports',
+ type: 'boolean',
+ default: false,
+ },
+ ],
+ examples: [
+ { command: 'claude-flow analyze imports src/', description: 'Analyze all imports' },
+ { command: 'claude-flow analyze imports src/ --external', description: 'Only npm packages' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const targetPath = ctx.args[0] || ctx.cwd;
+ const formatType = (ctx.flags.format as string) || 'text';
+ const outputFile = ctx.flags.output as string | undefined;
+ const externalOnly = ctx.flags.external as boolean;
+
+ output.printInfo(`Analyzing imports: ${output.highlight(targetPath)}`);
+ output.writeln();
+
+ const spinner = output.createSpinner({ text: 'Scanning imports...', spinner: 'dots' });
+ spinner.start();
+
+ try {
+ const astModule = await getASTAnalyzer();
+ const resolvedPath = resolve(targetPath);
+ const stat = await fs.stat(resolvedPath);
+ const files = stat.isDirectory() ? await scanSourceFiles(resolvedPath) : [resolvedPath];
+
+ const importCounts: Map<string, { count: number; files: string[] }> = new Map();
+ const fileImports: Map<string, string[]> = new Map();
+
+ for (const file of files.slice(0, 100)) {
+ try {
+ const content = await fs.readFile(file, 'utf-8');
+ let analysis;
+
+ if (astModule) {
+ const analyzer = astModule.createASTAnalyzer();
+ analysis = analyzer.analyze(content, file);
+ } else {
+ analysis = fallbackAnalyze(content, file);
+ }
+
+ const imports = analysis.imports.filter(imp => {
+ if (externalOnly) {
+ return !imp.startsWith('.') && !imp.startsWith('/');
+ }
+ return true;
+ });
+
+ fileImports.set(file, imports);
+
+ for (const imp of imports) {
+ const existing = importCounts.get(imp) || { count: 0, files: [] };
+ existing.count++;
+ existing.files.push(file);
+ importCounts.set(imp, existing);
+ }
+ } catch {
+ // Skip files that can't be parsed
+ }
+ }
+
+ spinner.stop();
+
+ // Sort by count
+ const sortedImports = Array.from(importCounts.entries())
+ .sort((a, b) => b[1].count - a[1].count);
+
+ if (formatType === 'json') {
+ const jsonOutput = {
+ imports: Object.fromEntries(sortedImports),
+ fileImports: Object.fromEntries(fileImports),
+ };
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ } else {
+ output.printJson(jsonOutput);
+ }
+ return { success: true, data: jsonOutput };
+ }
+
+ // Summary
+ const externalImports = sortedImports.filter(([imp]) => !imp.startsWith('.') && !imp.startsWith('/'));
+ const localImports = sortedImports.filter(([imp]) => imp.startsWith('.') || imp.startsWith('/'));
+
+ output.printBox(
+ [
+ `Total unique imports: ${sortedImports.length}`,
+ `External (npm): ${externalImports.length}`,
+ `Local (relative): ${localImports.length}`,
+ `Files scanned: ${files.length}`,
+ ].join('\n'),
+ 'Import Analysis'
+ );
+
+ // Most used imports
+ output.writeln();
+ output.writeln(output.bold('Most Used Imports'));
+ output.writeln(output.dim('-'.repeat(60)));
+
+ const topImports = sortedImports.slice(0, 20);
+ output.printTable({
+ columns: [
+ { key: 'count', header: 'Uses', width: 8, align: 'right' },
+ { key: 'import', header: 'Import', width: 50 },
+ { key: 'type', header: 'Type', width: 10 },
+ ],
+ data: topImports.map(([imp, data]) => ({
+ count: data.count,
+ import: imp,
+ type: imp.startsWith('.') || imp.startsWith('/') ? output.dim('local') : output.highlight('npm'),
+ })),
+ });
+
+ if (sortedImports.length > 20) {
+ output.writeln(output.dim(` ... and ${sortedImports.length - 20} more imports`));
+ }
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify({
+ imports: Object.fromEntries(sortedImports),
+ fileImports: Object.fromEntries(fileImports),
+ }, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ }
+
+ return { success: true, data: { imports: sortedImports } };
+ } catch (error) {
+ spinner.stop();
+ const message = error instanceof Error ? error.message : String(error);
+ output.printError(`Import analysis failed: ${message}`);
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+/**
+ * Helper: Scan directory for source files
+ */
+async function scanSourceFiles(dir: string, maxDepth: number = 10): Promise<string[]> {
+ const files: string[] = [];
+ const extensions = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
+ const excludeDirs = ['node_modules', 'dist', 'build', '.git', 'coverage', '__pycache__'];
+
+ async function scan(currentDir: string, depth: number): Promise<void> {
+ if (depth > maxDepth) return;
+
+ try {
+ const entries = await fs.readdir(currentDir, { withFileTypes: true });
+
+ for (const entry of entries) {
+ const fullPath = path.join(currentDir, entry.name);
+
+ if (entry.isDirectory()) {
+ if (!excludeDirs.includes(entry.name)) {
+ await scan(fullPath, depth + 1);
+ }
+ } else if (entry.isFile()) {
+ const ext = path.extname(entry.name);
+ if (extensions.includes(ext)) {
+ files.push(fullPath);
+ }
+ }
+ }
+ } catch {
+ // Skip directories we can't read
+ }
+ }
+
+ await scan(dir, 0);
+ return files;
+}
+
+/**
+ * Fallback analysis when ruvector is not available
+ */
+function fallbackAnalyze(code: string, filePath: string) {
+ const lines = code.split('\n');
+ const functions: Array<{ name: string; startLine: number; endLine: number }> = [];
+ const classes: Array<{ name: string; startLine: number; endLine: number }> = [];
+ const imports: string[] = [];
+ const exports: string[] = [];
+
+ // Extract functions
+ const funcPattern = /(?:export\s+)?(?:async\s+)?function\s+(\w+)|(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>|^\s*(?:async\s+)?(\w+)\s*\([^)]*\)\s*(?::\s*\w+)?\s*\{/gm;
+ let match;
+ while ((match = funcPattern.exec(code)) !== null) {
+ const name = match[1] || match[2] || match[3];
+ if (name && !['if', 'while', 'for', 'switch'].includes(name)) {
+ const lineNum = code.substring(0, match.index).split('\n').length;
+ functions.push({ name, startLine: lineNum, endLine: lineNum + 10 });
+ }
+ }
+
+ // Extract classes
+ const classPattern = /(?:export\s+)?class\s+(\w+)/gm;
+ while ((match = classPattern.exec(code)) !== null) {
+ const lineNum = code.substring(0, match.index).split('\n').length;
+ classes.push({ name: match[1], startLine: lineNum, endLine: lineNum + 20 });
+ }
+
+ // Extract imports
+ const importPattern = /import\s+(?:.*\s+from\s+)?['"]([^'"]+)['"]/gm;
+ while ((match = importPattern.exec(code)) !== null) {
+ imports.push(match[1]);
+ }
+ const requirePattern = /require\s*\(\s*['"]([^'"]+)['"]\s*\)/gm;
+ while ((match = requirePattern.exec(code)) !== null) {
+ imports.push(match[1]);
+ }
+
+ // Extract exports
+ const exportPattern = /export\s+(?:default\s+)?(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/gm;
+ while ((match = exportPattern.exec(code)) !== null) {
+ exports.push(match[1]);
+ }
+
+ // Calculate complexity
+ const nonEmptyLines = lines.filter(l => l.trim().length > 0).length;
+ const commentLines = lines.filter(l => /^\s*(\/\/|\/\*|\*|#)/.test(l)).length;
+ const decisionPoints = (code.match(/\b(if|else|for|while|switch|case|catch|&&|\|\||\?)\b/g) || []).length;
+
+ let cognitive = 0;
+ let nestingLevel = 0;
+ for (const line of lines) {
+ const opens = (line.match(/\{/g) || []).length;
+ const closes = (line.match(/\}/g) || []).length;
+ if (/\b(if|for|while|switch)\b/.test(line)) {
+ cognitive += 1 + nestingLevel;
+ }
+ nestingLevel = Math.max(0, nestingLevel + opens - closes);
+ }
+
+ // Detect language
+ const ext = path.extname(filePath).toLowerCase();
+ const language = ext === '.ts' || ext === '.tsx' ? 'typescript' :
+ ext === '.js' || ext === '.jsx' || ext === '.mjs' || ext === '.cjs' ? 'javascript' :
+ ext === '.py' ? 'python' : 'unknown';
+
+ return {
+ filePath,
+ language,
+ functions,
+ classes,
+ imports,
+ exports,
+ complexity: {
+ cyclomatic: decisionPoints + 1,
+ cognitive,
+ loc: nonEmptyLines,
+ commentDensity: lines.length > 0 ? commentLines / lines.length : 0,
+ },
+ };
+}
+
// Dependencies subcommand
const depsCommand: Command = {
name: 'deps',
description: 'Analyze project dependencies',
options: [
- { name: 'outdated', short: 'o', type: 'boolean', description: 'Show only outdated dependencies' },
- { name: 'security', short: 's', type: 'boolean', description: 'Check for security vulnerabilities' },
- { name: 'format', short: 'f', type: 'string', description: 'Output format: text, json', default: 'text' },
+ { name: 'outdated', short: 'o', type: 'boolean', description: 'Show only outdated dependencies' },
+ { name: 'security', short: 's', type: 'boolean', description: 'Check for security vulnerabilities' },
+ { name: 'format', short: 'f', type: 'string', description: 'Output format: text, json', default: 'text' },
+ ],
+ examples: [
+ { command: 'claude-flow analyze deps --outdated', description: 'Show outdated dependencies' },
+ { command: 'claude-flow analyze deps --security', description: 'Check for vulnerabilities' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const showOutdated = ctx.flags.outdated as boolean;
+ const checkSecurity = ctx.flags.security as boolean;
+
+ output.writeln();
+ output.writeln(output.bold('Dependency Analysis'));
+ output.writeln(output.dim('-'.repeat(50)));
+
+ output.printInfo('Analyzing dependencies...');
+ output.writeln();
+
+ // Placeholder - would integrate with npm/yarn audit
+ output.printBox(
+ [
+ `Outdated Check: ${showOutdated ? 'Enabled' : 'Disabled'}`,
+ `Security Check: ${checkSecurity ? 'Enabled' : 'Disabled'}`,
+ `Status: Feature in development`,
+ ``,
+ `Dependency analysis capabilities coming soon.`,
+ `Use 'security scan --type deps' for security scanning.`,
+ ].join('\n'),
+ 'Dependency Analysis'
+ );
+
+ return { success: true };
+ },
+};
+
+// ============================================================================
+// Graph Analysis Subcommands (MinCut, Louvain, Circular Dependencies)
+// ============================================================================
+
+/**
+ * Analyze code boundaries using MinCut algorithm
+ */
+const boundariesCommand: Command = {
+ name: 'boundaries',
+ aliases: ['boundary', 'mincut'],
+ description: 'Find natural code boundaries using MinCut algorithm',
+ options: [
+ {
+ name: 'partitions',
+ short: 'p',
+ description: 'Number of partitions to find',
+ type: 'number',
+ default: 2,
+ },
+ {
+ name: 'output',
+ short: 'o',
+ description: 'Output file path',
+ type: 'string',
+ },
+ {
+ name: 'format',
+ short: 'f',
+ description: 'Output format (text, json, dot)',
+ type: 'string',
+ default: 'text',
+ choices: ['text', 'json', 'dot'],
+ },
+ ],
+ examples: [
+ { command: 'claude-flow analyze boundaries src/', description: 'Find code boundaries in src/' },
+ { command: 'claude-flow analyze boundaries -p 3 src/', description: 'Find 3 partitions' },
+ { command: 'claude-flow analyze boundaries -f dot -o graph.dot src/', description: 'Export to DOT format' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const targetDir = ctx.args[0] || ctx.cwd;
+ const numPartitions = (ctx.flags.partitions as number) || 2;
+ const outputFile = ctx.flags.output as string | undefined;
+ const format = (ctx.flags.format as string) || 'text';
+
+ output.printInfo(`Analyzing code boundaries in: ${output.highlight(targetDir)}`);
+ output.writeln();
+
+ const spinner = output.createSpinner({ text: 'Building dependency graph...', spinner: 'dots' });
+ spinner.start();
+
+ try {
+ const analyzer = await getGraphAnalyzer();
+ if (!analyzer) {
+ spinner.stop();
+ output.printError('Graph analyzer module not available');
+ return { success: false, exitCode: 1 };
+ }
+
+ const result = await analyzer.analyzeGraph(resolve(targetDir), {
+ includeBoundaries: true,
+ includeModules: false,
+ numPartitions,
+ });
+
+ spinner.stop();
+
+ // Handle different output formats
+ if (format === 'json') {
+ const jsonOutput = {
+ boundaries: result.boundaries,
+ statistics: result.statistics,
+ circularDependencies: result.circularDependencies,
+ };
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ } else {
+ output.printJson(jsonOutput);
+ }
+
+ return { success: true, data: jsonOutput };
+ }
+
+ if (format === 'dot') {
+ const dotOutput = analyzer.exportToDot(result, {
+ includeLabels: true,
+ highlightCycles: true,
+ });
+
+ if (outputFile) {
+ await writeFile(outputFile, dotOutput);
+ output.printSuccess(`DOT graph written to ${outputFile}`);
+ output.writeln(output.dim('Visualize with: dot -Tpng -o graph.png ' + outputFile));
+ } else {
+ output.writeln(dotOutput);
+ }
+
+ return { success: true };
+ }
+
+ // Text format (default)
+ output.printBox(
+ [
+ `Files analyzed: ${result.statistics.nodeCount}`,
+ `Dependencies: ${result.statistics.edgeCount}`,
+ `Avg degree: ${result.statistics.avgDegree.toFixed(2)}`,
+ `Density: ${(result.statistics.density * 100).toFixed(2)}%`,
+ `Components: ${result.statistics.componentCount}`,
+ ].join('\n'),
+ 'Graph Statistics'
+ );
+
+ if (result.boundaries && result.boundaries.length > 0) {
+ output.writeln();
+ output.writeln(output.bold('MinCut Boundaries'));
+ output.writeln();
+
+ for (let i = 0; i < result.boundaries.length; i++) {
+ const boundary = result.boundaries[i];
+ output.writeln(output.bold(`Boundary ${i + 1} (cut value: ${boundary.cutValue})`));
+ output.writeln();
+
+ output.writeln(output.dim('Partition 1:'));
+ const p1Display = boundary.partition1.slice(0, 10);
+ output.printList(p1Display);
+ if (boundary.partition1.length > 10) {
+ output.writeln(output.dim(` ... and ${boundary.partition1.length - 10} more files`));
+ }
+
+ output.writeln();
+ output.writeln(output.dim('Partition 2:'));
+ const p2Display = boundary.partition2.slice(0, 10);
+ output.printList(p2Display);
+ if (boundary.partition2.length > 10) {
+ output.writeln(output.dim(` ... and ${boundary.partition2.length - 10} more files`));
+ }
+
+ output.writeln();
+ output.writeln(output.success('Suggestion:'));
+ output.writeln(` ${boundary.suggestion}`);
+ output.writeln();
+ }
+ }
+
+ // Show circular dependencies
+ if (result.circularDependencies.length > 0) {
+ output.writeln();
+ output.writeln(output.bold(output.warning('Circular Dependencies Detected')));
+ output.writeln();
+
+ for (const cycle of result.circularDependencies.slice(0, 5)) {
+ const severityColor = cycle.severity === 'high' ? output.error : cycle.severity === 'medium' ? output.warning : output.dim;
+ output.writeln(`${severityColor(`[${cycle.severity.toUpperCase()}]`)} ${cycle.cycle.join(' -> ')}`);
+ output.writeln(output.dim(` ${cycle.suggestion}`));
+ output.writeln();
+ }
+
+ if (result.circularDependencies.length > 5) {
+ output.writeln(output.dim(`... and ${result.circularDependencies.length - 5} more cycles`));
+ }
+ }
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(result, null, 2));
+ output.printSuccess(`Full results written to ${outputFile}`);
+ }
+
+ return { success: true, data: result };
+ } catch (error) {
+ spinner.stop();
+ const message = error instanceof Error ? error.message : String(error);
+ output.printError(`Analysis failed: ${message}`);
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+/**
+ * Analyze modules/communities using Louvain algorithm
+ */
+const modulesCommand: Command = {
+ name: 'modules',
+ aliases: ['communities', 'louvain'],
+ description: 'Detect module communities using Louvain algorithm',
+ options: [
+ {
+ name: 'output',
+ short: 'o',
+ description: 'Output file path',
+ type: 'string',
+ },
+ {
+ name: 'format',
+ short: 'f',
+ description: 'Output format (text, json, dot)',
+ type: 'string',
+ default: 'text',
+ choices: ['text', 'json', 'dot'],
+ },
+ {
+ name: 'min-size',
+ short: 'm',
+ description: 'Minimum community size to display',
+ type: 'number',
+ default: 2,
+ },
],
examples: [
- { command: 'claude-flow analyze deps --outdated', description: 'Show outdated dependencies' },
- { command: 'claude-flow analyze deps --security', description: 'Check for vulnerabilities' },
+ { command: 'claude-flow analyze modules src/', description: 'Detect module communities' },
+ { command: 'claude-flow analyze modules -f dot -o modules.dot src/', description: 'Export colored DOT graph' },
+ { command: 'claude-flow analyze modules -m 3 src/', description: 'Only show communities with 3+ files' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
- const showOutdated = ctx.flags.outdated as boolean;
- const checkSecurity = ctx.flags.security as boolean;
+ const targetDir = ctx.args[0] || ctx.cwd;
+ const outputFile = ctx.flags.output as string | undefined;
+ const format = (ctx.flags.format as string) || 'text';
+ const minSize = (ctx.flags['min-size'] as number) || 2;
+ output.printInfo(`Detecting module communities in: ${output.highlight(targetDir)}`);
output.writeln();
- output.writeln(output.bold('Dependency Analysis'));
- output.writeln(output.dim('-'.repeat(50)));
- output.printInfo('Analyzing dependencies...');
+ const spinner = output.createSpinner({ text: 'Building dependency graph...', spinner: 'dots' });
+ spinner.start();
+
+ try {
+ const analyzer = await getGraphAnalyzer();
+ if (!analyzer) {
+ spinner.stop();
+ output.printError('Graph analyzer module not available');
+ return { success: false, exitCode: 1 };
+ }
+
+ const result = await analyzer.analyzeGraph(resolve(targetDir), {
+ includeBoundaries: false,
+ includeModules: true,
+ });
+
+ spinner.stop();
+
+ // Filter communities by size
+ const communities = result.communities?.filter(c => c.members.length >= minSize) || [];
+
+ // Handle different output formats
+ if (format === 'json') {
+ const jsonOutput = {
+ communities,
+ statistics: result.statistics,
+ };
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ } else {
+ output.printJson(jsonOutput);
+ }
+
+ return { success: true, data: jsonOutput };
+ }
+
+ if (format === 'dot') {
+ const dotOutput = analyzer.exportToDot(result, {
+ includeLabels: true,
+ colorByCommunity: true,
+ highlightCycles: true,
+ });
+
+ if (outputFile) {
+ await writeFile(outputFile, dotOutput);
+ output.printSuccess(`DOT graph written to ${outputFile}`);
+ output.writeln(output.dim('Visualize with: dot -Tpng -o modules.png ' + outputFile));
+ } else {
+ output.writeln(dotOutput);
+ }
+
+ return { success: true };
+ }
+
+ // Text format (default)
+ output.printBox(
+ [
+ `Files analyzed: ${result.statistics.nodeCount}`,
+ `Dependencies: ${result.statistics.edgeCount}`,
+ `Communities found: ${result.communities?.length || 0}`,
+ `Showing: ${communities.length} (min size: ${minSize})`,
+ ].join('\n'),
+ 'Module Detection Results'
+ );
+
+ if (communities.length > 0) {
+ output.writeln();
+ output.writeln(output.bold('Detected Communities'));
+ output.writeln();
+
+ for (const community of communities.slice(0, 10)) {
+ const cohesionIndicator = community.cohesion > 0.5 ? output.success('High') :
+ community.cohesion > 0.2 ? output.warning('Medium') : output.dim('Low');
+
+ output.writeln(output.bold(`Community ${community.id}: ${community.suggestedName || 'unnamed'}`));
+ output.writeln(` ${output.dim('Cohesion:')} ${cohesionIndicator} (${(community.cohesion * 100).toFixed(1)}%)`);
+ output.writeln(` ${output.dim('Central node:')} ${community.centralNode || 'none'}`);
+ output.writeln(` ${output.dim('Members:')} ${community.members.length} files`);
+
+ const displayMembers = community.members.slice(0, 5);
+ for (const member of displayMembers) {
+ output.writeln(` - ${member}`);
+ }
+ if (community.members.length > 5) {
+ output.writeln(output.dim(` ... and ${community.members.length - 5} more`));
+ }
+ output.writeln();
+ }
+
+ if (communities.length > 10) {
+ output.writeln(output.dim(`... and ${communities.length - 10} more communities`));
+ }
+ }
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(result, null, 2));
+ output.printSuccess(`Full results written to ${outputFile}`);
+ }
+
+ return { success: true, data: result };
+ } catch (error) {
+ spinner.stop();
+ const message = error instanceof Error ? error.message : String(error);
+ output.printError(`Analysis failed: ${message}`);
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+/**
+ * Build and export dependency graph
+ */
+const dependenciesCommand: Command = {
+ name: 'dependencies',
+ aliases: ['graph'],
+ description: 'Build and export full dependency graph',
+ options: [
+ {
+ name: 'output',
+ short: 'o',
+ description: 'Output file path',
+ type: 'string',
+ },
+ {
+ name: 'format',
+ short: 'f',
+ description: 'Output format (text, json, dot)',
+ type: 'string',
+ default: 'text',
+ choices: ['text', 'json', 'dot'],
+ },
+ {
+ name: 'include',
+ short: 'i',
+ description: 'File extensions to include (comma-separated)',
+ type: 'string',
+ default: '.ts,.tsx,.js,.jsx,.mjs,.cjs',
+ },
+ {
+ name: 'exclude',
+ short: 'e',
+ description: 'Patterns to exclude (comma-separated)',
+ type: 'string',
+ default: 'node_modules,dist,build,.git',
+ },
+ {
+ name: 'depth',
+ short: 'd',
+ description: 'Maximum directory depth',
+ type: 'number',
+ default: 10,
+ },
+ ],
+ examples: [
+ { command: 'claude-flow analyze dependencies src/', description: 'Build dependency graph' },
+ { command: 'claude-flow analyze dependencies -f dot -o deps.dot src/', description: 'Export to DOT' },
+ { command: 'claude-flow analyze dependencies -i .ts,.tsx src/', description: 'Only TypeScript files' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const targetDir = ctx.args[0] || ctx.cwd;
+ const outputFile = ctx.flags.output as string | undefined;
+ const format = (ctx.flags.format as string) || 'text';
+ const include = ((ctx.flags.include as string) || '.ts,.tsx,.js,.jsx,.mjs,.cjs').split(',');
+ const exclude = ((ctx.flags.exclude as string) || 'node_modules,dist,build,.git').split(',');
+ const maxDepth = (ctx.flags.depth as number) || 10;
+
+ output.printInfo(`Building dependency graph for: ${output.highlight(targetDir)}`);
output.writeln();
- // Placeholder - would integrate with npm/yarn audit
- output.printBox(
- [
- `Outdated Check: ${showOutdated ? 'Enabled' : 'Disabled'}`,
- `Security Check: ${checkSecurity ? 'Enabled' : 'Disabled'}`,
- `Status: Feature in development`,
- ``,
- `Dependency analysis capabilities coming soon.`,
- `Use 'security scan --type deps' for security scanning.`,
- ].join('\n'),
- 'Dependency Analysis'
- );
+ const spinner = output.createSpinner({ text: 'Scanning files...', spinner: 'dots' });
+ spinner.start();
- return { success: true };
+ try {
+ const analyzer = await getGraphAnalyzer();
+ if (!analyzer) {
+ spinner.stop();
+ output.printError('Graph analyzer module not available');
+ return { success: false, exitCode: 1 };
+ }
+
+ const graph = await analyzer.buildDependencyGraph(resolve(targetDir), {
+ include,
+ exclude,
+ maxDepth,
+ });
+
+ spinner.stop();
+
+ // Detect circular dependencies
+ const circularDeps = analyzer.detectCircularDependencies(graph);
+
+ // Handle different output formats
+ if (format === 'json') {
+ const jsonOutput = {
+ nodes: Array.from(graph.nodes.values()),
+ edges: graph.edges,
+ metadata: graph.metadata,
+ circularDependencies: circularDeps,
+ };
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
+ output.printSuccess(`Graph written to ${outputFile}`);
+ } else {
+ output.printJson(jsonOutput);
+ }
+
+ return { success: true, data: jsonOutput };
+ }
+
+ if (format === 'dot') {
+ const result = { graph, circularDependencies: circularDeps, statistics: {
+ nodeCount: graph.nodes.size,
+ edgeCount: graph.edges.length,
+ avgDegree: 0,
+ maxDegree: 0,
+ density: 0,
+ componentCount: 0,
+ }};
+
+ const dotOutput = analyzer.exportToDot(result, {
+ includeLabels: true,
+ highlightCycles: true,
+ });
+
+ if (outputFile) {
+ await writeFile(outputFile, dotOutput);
+ output.printSuccess(`DOT graph written to ${outputFile}`);
+ output.writeln(output.dim('Visualize with: dot -Tpng -o deps.png ' + outputFile));
+ } else {
+ output.writeln(dotOutput);
+ }
+
+ return { success: true };
+ }
+
+ // Text format (default)
+ output.printBox(
+ [
+ `Files: ${graph.metadata.totalFiles}`,
+ `Dependencies: ${graph.metadata.totalEdges}`,
+ `Build time: ${graph.metadata.buildTime}ms`,
+ `Root: ${graph.metadata.rootDir}`,
+ ].join('\n'),
+ 'Dependency Graph'
+ );
+
+ // Show top files by imports
+ output.writeln();
+ output.writeln(output.bold('Most Connected Files'));
+ output.writeln();
+
+ const nodesByDegree = Array.from(graph.nodes.values())
+ .map(n => ({
+ ...n,
+ degree: graph.edges.filter(e => e.source === n.id || e.target === n.id).length,
+ }))
+ .sort((a, b) => b.degree - a.degree)
+ .slice(0, 10);
+
+ output.printTable({
+ columns: [
+ { key: 'path', header: 'File', width: 50 },
+ { key: 'degree', header: 'Connections', width: 12, align: 'right' },
+ { key: 'complexity', header: 'Complexity', width: 12, align: 'right' },
+ ],
+ data: nodesByDegree.map(n => ({
+ path: n.path.length > 48 ? '...' + n.path.slice(-45) : n.path,
+ degree: n.degree,
+ complexity: n.complexity || 0,
+ })),
+ });
+
+ // Show circular dependencies
+ if (circularDeps.length > 0) {
+ output.writeln();
+ output.writeln(output.bold(output.warning(`Circular Dependencies: ${circularDeps.length}`)));
+ output.writeln();
+
+ for (const cycle of circularDeps.slice(0, 3)) {
+ output.writeln(` ${cycle.cycle.join(' -> ')}`);
+ }
+ if (circularDeps.length > 3) {
+ output.writeln(output.dim(` ... and ${circularDeps.length - 3} more`));
+ }
+ }
+
+ if (outputFile) {
+ const fullOutput = {
+ nodes: Array.from(graph.nodes.values()),
+ edges: graph.edges,
+ metadata: graph.metadata,
+ circularDependencies: circularDeps,
+ };
+ await writeFile(outputFile, JSON.stringify(fullOutput, null, 2));
+ output.printSuccess(`Full results written to ${outputFile}`);
+ }
+
+ return { success: true };
+ } catch (error) {
+ spinner.stop();
+ const message = error instanceof Error ? error.message : String(error);
+ output.printError(`Analysis failed: ${message}`);
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+/**
+ * Detect circular dependencies
+ */
+const circularCommand: Command = {
+ name: 'circular',
+ aliases: ['cycles'],
+ description: 'Detect circular dependencies in codebase',
+ options: [
+ {
+ name: 'output',
+ short: 'o',
+ description: 'Output file path',
+ type: 'string',
+ },
+ {
+ name: 'format',
+ short: 'f',
+ description: 'Output format (text, json)',
+ type: 'string',
+ default: 'text',
+ choices: ['text', 'json'],
+ },
+ {
+ name: 'severity',
+ short: 's',
+ description: 'Minimum severity to show (low, medium, high)',
+ type: 'string',
+ default: 'low',
+ choices: ['low', 'medium', 'high'],
+ },
+ ],
+ examples: [
+ { command: 'claude-flow analyze circular src/', description: 'Find circular dependencies' },
+ { command: 'claude-flow analyze circular -s high src/', description: 'Only high severity cycles' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const targetDir = ctx.args[0] || ctx.cwd;
+ const outputFile = ctx.flags.output as string | undefined;
+ const format = (ctx.flags.format as string) || 'text';
+ const minSeverity = (ctx.flags.severity as string) || 'low';
+
+ output.printInfo(`Detecting circular dependencies in: ${output.highlight(targetDir)}`);
+ output.writeln();
+
+ const spinner = output.createSpinner({ text: 'Analyzing dependencies...', spinner: 'dots' });
+ spinner.start();
+
+ try {
+ const analyzer = await getGraphAnalyzer();
+ if (!analyzer) {
+ spinner.stop();
+ output.printError('Graph analyzer module not available');
+ return { success: false, exitCode: 1 };
+ }
+
+ const graph = await analyzer.buildDependencyGraph(resolve(targetDir));
+ const cycles = analyzer.detectCircularDependencies(graph);
+
+ spinner.stop();
+
+ // Filter by severity
+ const severityOrder = { low: 0, medium: 1, high: 2 };
+ const minLevel = severityOrder[minSeverity as keyof typeof severityOrder] || 0;
+ const filtered = cycles.filter(c => severityOrder[c.severity] >= minLevel);
+
+ if (format === 'json') {
+ const jsonOutput = { cycles: filtered, total: cycles.length, filtered: filtered.length };
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify(jsonOutput, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ } else {
+ output.printJson(jsonOutput);
+ }
+
+ return { success: true, data: jsonOutput };
+ }
+
+ // Text format
+ if (filtered.length === 0) {
+ output.printSuccess('No circular dependencies found!');
+ return { success: true };
+ }
+
+ output.printBox(
+ [
+ `Total cycles: ${cycles.length}`,
+ `Shown (${minSeverity}+): ${filtered.length}`,
+ `High severity: ${cycles.filter(c => c.severity === 'high').length}`,
+ `Medium severity: ${cycles.filter(c => c.severity === 'medium').length}`,
+ `Low severity: ${cycles.filter(c => c.severity === 'low').length}`,
+ ].join('\n'),
+ 'Circular Dependencies'
+ );
+
+ output.writeln();
+
+ // Group by severity
+ const grouped = {
+ high: filtered.filter(c => c.severity === 'high'),
+ medium: filtered.filter(c => c.severity === 'medium'),
+ low: filtered.filter(c => c.severity === 'low'),
+ };
+
+ for (const [severity, items] of Object.entries(grouped)) {
+ if (items.length === 0) continue;
+
+ const color = severity === 'high' ? output.error : severity === 'medium' ? output.warning : output.dim;
+ output.writeln(color(output.bold(`${severity.toUpperCase()} SEVERITY (${items.length})`)));
+ output.writeln();
+
+ for (const cycle of items.slice(0, 5)) {
+ output.writeln(` ${cycle.cycle.join(' -> ')}`);
+ output.writeln(output.dim(` Fix: ${cycle.suggestion}`));
+ output.writeln();
+ }
+
+ if (items.length > 5) {
+ output.writeln(output.dim(` ... and ${items.length - 5} more ${severity} cycles`));
+ output.writeln();
+ }
+ }
+
+ if (outputFile) {
+ await writeFile(outputFile, JSON.stringify({ cycles: filtered }, null, 2));
+ output.printSuccess(`Results written to ${outputFile}`);
+ }
+
+ return { success: true, data: { cycles: filtered } };
+ } catch (error) {
+ spinner.stop();
+ const message = error instanceof Error ? error.message : String(error);
+ output.printError(`Analysis failed: ${message}`);
+ return { success: false, exitCode: 1 };
+ }
},
};
@@ -411,12 +2019,20 @@ function getStatusDisplay(status: string): string {
// Main analyze command
export const analyzeCommand: Command = {
name: 'analyze',
- description: 'Code analysis, diff classification, and change risk assessment',
+ description: 'Code analysis, diff classification, graph boundaries, and change risk assessment',
aliases: ['an'],
subcommands: [
diffCommand,
codeCommand,
depsCommand,
+ astCommand,
+ complexityAstCommand,
+ symbolsCommand,
+ importsCommand,
+ boundariesCommand,
+ modulesCommand,
+ dependenciesCommand,
+ circularCommand,
],
options: [
{
@@ -428,10 +2044,15 @@ export const analyzeCommand: Command = {
},
],
examples: [
+ { command: 'claude-flow analyze ast src/', description: 'Analyze code with AST parsing' },
+ { command: 'claude-flow analyze complexity src/ --threshold 15', description: 'Find high-complexity files' },
+ { command: 'claude-flow analyze symbols src/ --type function', description: 'Extract all functions' },
+ { command: 'claude-flow analyze imports src/ --external', description: 'List npm dependencies' },
{ command: 'claude-flow analyze diff --risk', description: 'Analyze diff with risk assessment' },
- { command: 'claude-flow analyze diff HEAD~1 --classify', description: 'Classify changes from last commit' },
- { command: 'claude-flow analyze diff main..feature --format json', description: 'Compare branches with JSON output' },
- { command: 'claude-flow analyze code -p ./src', description: 'Run code analysis' },
+ { command: 'claude-flow analyze boundaries src/', description: 'Find code boundaries using MinCut' },
+ { command: 'claude-flow analyze modules src/', description: 'Detect module communities with Louvain' },
+ { command: 'claude-flow analyze dependencies src/ --format dot', description: 'Export dependency graph as DOT' },
+ { command: 'claude-flow analyze circular src/', description: 'Find circular dependencies' },
{ command: 'claude-flow analyze deps --security', description: 'Check dependency vulnerabilities' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
@@ -443,12 +2064,37 @@ export const analyzeCommand: Command = {
output.writeln(output.bold('Available subcommands:'));
output.writeln();
- output.writeln(` ${output.highlight('diff')} Analyze git diff for change risk and classification`);
- output.writeln(` ${output.highlight('code')} Static code analysis and quality assessment`);
- output.writeln(` ${output.highlight('deps')} Analyze project dependencies`);
+ output.writeln(` ${output.highlight('diff')} Analyze git diff for change risk and classification`);
+ output.writeln(` ${output.highlight('code')} Static code analysis and quality assessment`);
+ output.writeln(` ${output.highlight('deps')} Analyze project dependencies`);
+ output.writeln(` ${output.highlight('ast')} AST analysis with symbol extraction and complexity`);
+ output.writeln(` ${output.highlight('complexity')} Analyze cyclomatic and cognitive complexity`);
+ output.writeln(` ${output.highlight('symbols')} Extract functions, classes, and types`);
+ output.writeln(` ${output.highlight('imports')} Analyze import dependencies`);
+ output.writeln(` ${output.highlight('boundaries')} Find code boundaries using MinCut algorithm`);
+ output.writeln(` ${output.highlight('modules')} Detect module communities using Louvain algorithm`);
+ output.writeln(` ${output.highlight('dependencies')} Build and export full dependency graph`);
+ output.writeln(` ${output.highlight('circular')} Detect circular dependencies in codebase`);
+ output.writeln();
+
+ output.writeln(output.bold('AST Analysis Examples:'));
+ output.writeln();
+ output.writeln(` ${output.dim('claude-flow analyze ast src/')} # Full AST analysis`);
+ output.writeln(` ${output.dim('claude-flow analyze ast src/index.ts -c')} # Include complexity`);
+ output.writeln(` ${output.dim('claude-flow analyze complexity src/ -t 15')} # Flag high complexity`);
+ output.writeln(` ${output.dim('claude-flow analyze symbols src/ --type fn')} # Extract functions`);
+ output.writeln(` ${output.dim('claude-flow analyze imports src/ --external')} # Only npm imports`);
+ output.writeln();
+
+ output.writeln(output.bold('Graph Analysis Examples:'));
+ output.writeln();
+ output.writeln(` ${output.dim('claude-flow analyze boundaries src/')} # Find natural code boundaries`);
+ output.writeln(` ${output.dim('claude-flow analyze modules src/')} # Detect module communities`);
+ output.writeln(` ${output.dim('claude-flow analyze dependencies -f dot src/')} # Export to DOT format`);
+ output.writeln(` ${output.dim('claude-flow analyze circular src/')} # Find circular deps`);
output.writeln();
- output.writeln(output.bold('Examples:'));
+ output.writeln(output.bold('Diff Analysis Examples:'));
output.writeln();
output.writeln(` ${output.dim('claude-flow analyze diff --risk')} # Risk assessment`);
output.writeln(` ${output.dim('claude-flow analyze diff HEAD~1 --classify')} # Classify changes`);
diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.ts
index 2a989584b9..25fe70f9af 100644
--- a/v3/@claude-flow/cli/src/commands/hooks.ts
+++ b/v3/@claude-flow/cli/src/commands/hooks.ts
@@ -2515,7 +2515,7 @@ const coverageRouteCommand: Command = {
return { success: false, exitCode: 1 };
}
- const spinner = output.createSpinner('Analyzing coverage and routing task...');
+ const spinner = output.createSpinner({ text: 'Analyzing coverage and routing task...' });
spinner.start();
try {
@@ -2655,7 +2655,7 @@ const coverageSuggestCommand: Command = {
return { success: false, exitCode: 1 };
}
- const spinner = output.createSpinner(`Analyzing coverage for ${path}...`);
+ const spinner = output.createSpinner({ text: `Analyzing coverage for ${path}...` });
spinner.start();
try {
@@ -2777,7 +2777,7 @@ const coverageGapsCommand: Command = {
const groupByAgent = ctx.flags['group-by-agent'] !== false;
const criticalOnly = ctx.flags['critical-only'] as boolean || false;
- const spinner = output.createSpinner('Analyzing project coverage gaps...');
+ const spinner = output.createSpinner({ text: 'Analyzing project coverage gaps...' });
spinner.start();
try {
diff --git a/v3/@claude-flow/cli/src/commands/index.ts b/v3/@claude-flow/cli/src/commands/index.ts
index 391671e206..ebab355625 100644
--- a/v3/@claude-flow/cli/src/commands/index.ts
+++ b/v3/@claude-flow/cli/src/commands/index.ts
@@ -109,6 +109,8 @@ export const commands: Command[] = [
doctorCommand,
// Analysis Commands
analyzeCommand,
+ // Q-Learning Routing Commands
+ routeCommand,
];
/**
diff --git a/v3/@claude-flow/cli/src/commands/route.ts b/v3/@claude-flow/cli/src/commands/route.ts
index 6d21ee8869..2eac154fab 100644
--- a/v3/@claude-flow/cli/src/commands/route.ts
+++ b/v3/@claude-flow/cli/src/commands/route.ts
@@ -13,25 +13,65 @@
import type { Command, CommandContext, CommandResult } from '../types.js';
import { output } from '../output.js';
+import {
+ createQLearningRouter,
+ isRuvectorAvailable,
+ type QLearningRouter,
+ type RouteDecision,
+} from '../ruvector/index.js';
// ============================================================================
-// Helper Functions (avoid top-level await)
+// Agent Type Definitions
// ============================================================================
-async function getRouterModule() {
- try {
- return await import('../ruvector/q-learning-router.js');
- } catch {
- return null;
- }
+interface AgentType {
+ id: string;
+ name: string;
+ description: string;
+ capabilities: string[];
+ priority: number;
}
-async function getRuVectorModule() {
- try {
- return await import('../ruvector/index.js');
- } catch {
- return null;
+/**
+ * Available agent types for routing
+ */
+const AGENT_TYPES: AgentType[] = [
+ { id: 'coder', name: 'Coder', description: 'Implements features and writes code', capabilities: ['coding', 'implementation', 'refactoring'], priority: 1 },
+ { id: 'tester', name: 'Tester', description: 'Creates tests and validates functionality', capabilities: ['testing', 'validation', 'quality'], priority: 2 },
+ { id: 'reviewer', name: 'Reviewer', description: 'Reviews code quality and security', capabilities: ['review', 'security', 'best-practices'], priority: 3 },
+ { id: 'architect', name: 'Architect', description: 'Designs system architecture', capabilities: ['design', 'architecture', 'planning'], priority: 4 },
+ { id: 'researcher', name: 'Researcher', description: 'Researches requirements and patterns', capabilities: ['research', 'analysis', 'documentation'], priority: 5 },
+ { id: 'optimizer', name: 'Optimizer', description: 'Optimizes performance and efficiency', capabilities: ['optimization', 'performance', 'profiling'], priority: 6 },
+ { id: 'debugger', name: 'Debugger', description: 'Debugs issues and fixes bugs', capabilities: ['debugging', 'troubleshooting', 'fixing'], priority: 7 },
+ { id: 'documenter', name: 'Documenter', description: 'Creates and updates documentation', capabilities: ['documentation', 'writing', 'explaining'], priority: 8 },
+];
+
+// ============================================================================
+// Router Singleton
+// ============================================================================
+
+let routerInstance: QLearningRouter | null = null;
+let routerInitialized = false;
+
+/**
+ * Get or create the router instance
+ */
+async function getRouter(): Promise<QLearningRouter> {
+ if (!routerInstance) {
+ routerInstance = createQLearningRouter();
}
+ if (!routerInitialized) {
+ await routerInstance.initialize();
+ routerInitialized = true;
+ }
+ return routerInstance;
+}
+
+/**
+ * Get agent type by route name
+ */
+function getAgentType(route: string): AgentType | undefined {
+ return AGENT_TYPES.find(a => a.id === route);
}
// ============================================================================
@@ -87,26 +127,20 @@ const routeTaskCommand: Command = {
return { success: false, exitCode: 1 };
}
- const routerModule = await getRouterModule();
- if (!routerModule) {
- output.printError('Router module not available');
- return { success: false, exitCode: 1 };
- }
-
const spinner = output.createSpinner({ text: 'Analyzing task...', spinner: 'dots' });
spinner.start();
try {
if (forceAgent) {
// Bypass Q-Learning, use specified agent
- const agents = await routerModule.listAgentTypes();
- const agent = agents.find(a => a.id === forceAgent || a.name.toLowerCase() === forceAgent.toLowerCase());
+ const agent = getAgentType(forceAgent) ||
+ AGENT_TYPES.find(a => a.name.toLowerCase() === forceAgent.toLowerCase());
if (!agent) {
spinner.fail(`Agent "${forceAgent}" not found`);
output.writeln();
output.writeln('Available agents:');
- output.printList(agents.map(a => `${output.highlight(a.id)} - ${a.description}`));
+ output.printList(AGENT_TYPES.map(a => `${output.highlight(a.id)} - ${a.description}`));
return { success: false, exitCode: 1 };
}
@@ -134,23 +168,24 @@ const routeTaskCommand: Command = {
}
// Use Q-Learning routing
- const result = await routerModule.routeTask(taskDescription, useExploration);
+ const router = await getRouter();
+ const result: RouteDecision = router.route(taskDescription, useExploration);
+ const agent = getAgentType(result.route) || AGENT_TYPES[0];
- spinner.succeed(`Routed to ${result.agentType.name}`);
+ spinner.succeed(`Routed to ${agent.name}`);
if (jsonOutput) {
output.printJson({
task: taskDescription,
- agentId: result.agentId,
- agentName: result.agentType.name,
+ agentId: result.route,
+ agentName: agent.name,
confidence: result.confidence,
- qValue: result.qValue,
- explorationUsed: result.explorationUsed,
+ qValues: result.qValues,
+ explored: result.explored,
alternatives: result.alternatives.map(a => ({
- agentId: a.agentId,
- agentName: a.agentType.name,
- confidence: a.confidence,
- qValue: a.qValue,
+ agentId: a.route,
+ agentName: getAgentType(a.route)?.name || a.route,
+ score: a.score,
})),
});
} else {
@@ -165,13 +200,13 @@ const routeTaskCommand: Command = {
output.printBox([
`Task: ${taskDescription}`,
``,
- `Agent: ${output.highlight(result.agentType.name)} (${result.agentId})`,
+ `Agent: ${output.highlight(agent.name)} (${result.route})`,
`Confidence: ${confidenceColor(`${(result.confidence * 100).toFixed(1)}%`)}`,
- `Q-Value: ${result.qValue.toFixed(3)}`,
- `Exploration: ${result.explorationUsed ? output.warning('Yes') : 'No'}`,
+ `Q-Value: ${Math.max(...result.qValues).toFixed(3)}`,
+ `Exploration: ${result.explored ? output.warning('Yes') : 'No'}`,
``,
- `Description: ${result.agentType.description}`,
- `Capabilities: ${result.agentType.capabilities.join(', ')}`,
+ `Description: ${agent.description}`,
+ `Capabilities: ${agent.capabilities.join(', ')}`,
].join('\n'), 'Q-Learning Routing');
if (result.alternatives.length > 0) {
@@ -180,19 +215,17 @@ const routeTaskCommand: Command = {
output.printTable({
columns: [
{ key: 'agent', header: 'Agent', width: 20 },
- { key: 'confidence', header: 'Confidence', width: 12, align: 'right' },
- { key: 'qValue', header: 'Q-Value', width: 10, align: 'right' },
+ { key: 'score', header: 'Score', width: 12, align: 'right' },
],
data: result.alternatives.map(a => ({
- agent: a.agentType.name,
- confidence: `${(a.confidence * 100).toFixed(1)}%`,
- qValue: a.qValue.toFixed(3),
+ agent: getAgentType(a.route)?.name || a.route,
+ score: a.score.toFixed(3),
})),
});
}
}
- return { success: true, data: result };
+ return { success: true, data: { agentId: result.route, result } };
} catch (error) {
spinner.fail('Routing failed');
output.printError(error instanceof Error ? error.message : String(error));
@@ -225,17 +258,9 @@ const listAgentsCommand: Command = {
action: async (ctx: CommandContext): Promise<CommandResult> => {
const jsonOutput = ctx.flags.json as boolean;
- const routerModule = await getRouterModule();
- if (!routerModule) {
- output.printError('Router module not available');
- return { success: false, exitCode: 1 };
- }
-
try {
- const agents = await routerModule.listAgentTypes();
-
if (jsonOutput) {
- output.printJson(agents);
+ output.printJson(AGENT_TYPES);
} else {
output.writeln();
output.writeln(output.bold('Available Agent Types'));
@@ -244,12 +269,12 @@ const listAgentsCommand: Command = {
output.printTable({
columns: [
- { key: 'id', header: 'ID', width: 20 },
- { key: 'name', header: 'Name', width: 20 },
+ { key: 'id', header: 'ID', width: 15 },
+ { key: 'name', header: 'Name', width: 15 },
{ key: 'priority', header: 'Priority', width: 10, align: 'right' },
- { key: 'description', header: 'Description', width: 40 },
+ { key: 'description', header: 'Description', width: 45 },
],
- data: agents.map(a => ({
+ data: AGENT_TYPES.map(a => ({
id: output.highlight(a.id),
name: a.name,
priority: String(a.priority),
@@ -258,10 +283,10 @@ const listAgentsCommand: Command = {
});
output.writeln();
- output.writeln(output.dim(`Total: ${agents.length} agent types`));
+ output.writeln(output.dim(`Total: ${AGENT_TYPES.length} agent types`));
}
- return { success: true, data: agents };
+ return { success: true, data: AGENT_TYPES };
} catch (error) {
output.printError(error instanceof Error ? error.message : String(error));
return { success: false, exitCode: 1 };
@@ -291,20 +316,15 @@ const statsCommand: Command = {
action: async (ctx: CommandContext): Promise<CommandResult> => {
const jsonOutput = ctx.flags.json as boolean;
- const routerModule = await getRouterModule();
- const ruvectorModule = await getRuVectorModule();
-
- if (!routerModule) {
- output.printError('Router module not available');
- return { success: false, exitCode: 1 };
- }
-
try {
- const stats = await routerModule.getRouterStats();
- const ruvectorStatus = ruvectorModule?.getStatus?.() ?? {
- available: false,
- wasmAccelerated: false,
- backend: 'fallback',
+ const router = await getRouter();
+ const stats = router.getStats();
+ const ruvectorAvailable = await isRuvectorAvailable();
+
+ const ruvectorStatus = {
+ available: ruvectorAvailable,
+ wasmAccelerated: stats.useNative === 1,
+ backend: stats.useNative === 1 ? 'ruvector-native' : 'fallback',
};
if (jsonOutput) {
@@ -320,38 +340,15 @@ const statsCommand: Command = {
{ key: 'value', header: 'Value', width: 20, align: 'right' },
],
data: [
- { metric: 'Total Routes', value: String(stats.totalRoutes) },
- { metric: 'Successful Routes', value: String(stats.successfulRoutes) },
- { metric: 'Success Rate', value: stats.totalRoutes > 0
- ? `${((stats.successfulRoutes / stats.totalRoutes) * 100).toFixed(1)}%`
- : 'N/A' },
- { metric: 'Avg Confidence', value: `${(stats.avgConfidence * 100).toFixed(1)}%` },
- { metric: 'Avg Execution Time', value: `${stats.avgExecutionTime.toFixed(0)}ms` },
+ { metric: 'Update Count', value: String(stats.updateCount) },
{ metric: 'Q-Table Size', value: String(stats.qTableSize) },
- { metric: 'Epsilon', value: stats.epsilon.toFixed(3) },
- { metric: 'Backend', value: stats.backend },
+ { metric: 'Step Count', value: String(stats.stepCount) },
+ { metric: 'Epsilon', value: stats.epsilon.toFixed(4) },
+ { metric: 'Avg TD Error', value: stats.avgTDError.toFixed(4) },
+ { metric: 'Native Backend', value: stats.useNative === 1 ? 'Yes' : 'No' },
],
});
- if (Object.keys(stats.agentUsage).length > 0) {
- output.writeln();
- output.writeln(output.bold('Agent Usage'));
- output.printTable({
- columns: [
- { key: 'agent', header: 'Agent', width: 20 },
- { key: 'count', header: 'Routes', width: 10, align: 'right' },
- { key: 'percentage', header: '%', width: 10, align: 'right' },
- ],
- data: Object.entries(stats.agentUsage)
- .sort((a, b) => b[1] - a[1])
- .map(([agent, count]) => ({
- agent,
- count: String(count),
- percentage: `${((count / stats.totalRoutes) * 100).toFixed(1)}%`,
- })),
- });
- }
-
output.writeln();
output.writeln(output.bold('RuVector Status'));
output.printList([
@@ -378,9 +375,9 @@ const feedbackCommand: Command = {
description: 'Provide feedback on a routing decision',
options: [
{
- name: 'task-id',
+ name: 'task',
short: 't',
- description: 'Task identifier',
+ description: 'Task description (context for learning)',
type: 'string',
required: true,
},
@@ -392,68 +389,59 @@ const feedbackCommand: Command = {
required: true,
},
{
- name: 'success',
- short: 's',
- description: 'Whether the routing was successful',
- type: 'boolean',
- default: true,
- },
- {
- name: 'quality',
- short: 'q',
- description: 'Quality score (0-1)',
+ name: 'reward',
+ short: 'r',
+ description: 'Reward value (-1 to 1, where 1 is best)',
type: 'number',
default: 0.8,
},
{
- name: 'time',
- description: 'Execution time in milliseconds',
- type: 'number',
- default: 1000,
+ name: 'next-task',
+ short: 'n',
+ description: 'Next task description (for multi-step learning)',
+ type: 'string',
},
],
examples: [
- { command: 'claude-flow route feedback -t "auth-impl" -a coder -s true -q 0.9', description: 'Positive feedback' },
- { command: 'claude-flow route feedback -t "test-write" -a tester -s false', description: 'Negative feedback' },
+ { command: 'claude-flow route feedback -t "implement auth" -a coder -r 0.9', description: 'Positive feedback' },
+ { command: 'claude-flow route feedback -t "write tests" -a tester -r -0.5', description: 'Negative feedback' },
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
- const taskId = ctx.flags['task-id'] as string;
+ const taskDescription = ctx.flags.task as string;
const agentId = ctx.flags.agent as string;
- const success = ctx.flags.success as boolean;
- const quality = ctx.flags.quality as number;
- const executionTime = ctx.flags.time as number;
+ const reward = ctx.flags.reward as number;
+ const nextTask = ctx.flags['next-task'] as string | undefined;
- if (!taskId || !agentId) {
- output.printError('Task ID and agent are required');
+ if (!taskDescription || !agentId) {
+ output.printError('Task description and agent are required');
return { success: false, exitCode: 1 };
}
- const routerModule = await getRouterModule();
- if (!routerModule) {
- output.printError('Router module not available');
+ // Validate agent
+ const agent = getAgentType(agentId);
+ if (!agent) {
+ output.printError(`Unknown agent: ${agentId}`);
+ output.writeln('Available agents:');
+ output.printList(AGENT_TYPES.map(a => a.id));
return { success: false, exitCode: 1 };
}
try {
- await routerModule.provideFeedback({
- taskId,
- agentId,
- success,
- quality: Math.max(0, Math.min(1, quality)),
- executionTimeMs: executionTime,
- });
-
- output.printSuccess(`Feedback recorded for task "${taskId}"`);
+ const router = await getRouter();
+ const clampedReward = Math.max(-1, Math.min(1, reward));
+ const tdError = router.update(taskDescription, agentId, clampedReward, nextTask);
+
+ output.printSuccess(`Feedback recorded for agent "${agent.name}"`);
output.writeln();
output.printBox([
- `Task: ${taskId}`,
- `Agent: ${agentId}`,
- `Success: ${success ? output.success('Yes') : output.error('No')}`,
- `Quality: ${(quality * 100).toFixed(0)}%`,
- `Time: ${executionTime}ms`,
- ].join('\n'), 'Feedback Recorded');
-
- return { success: true };
+ `Task: ${taskDescription}`,
+ `Agent: ${agent.name} (${agentId})`,
+ `Reward: ${clampedReward >= 0 ? output.success(clampedReward.toFixed(2)) : output.error(clampedReward.toFixed(2))}`,
+ `TD Error: ${Math.abs(tdError).toFixed(4)}`,
+ nextTask ? `Next Task: ${nextTask}` : '',
+ ].filter(Boolean).join('\n'), 'Feedback Recorded');
+
+ return { success: true, data: { tdError } };
} catch (error) {
output.printError(error instanceof Error ? error.message : String(error));
return { success: false, exitCode: 1 };
@@ -490,16 +478,94 @@ const resetCommand: Command = {
return { success: false, exitCode: 1 };
}
- const routerModule = await getRouterModule();
- if (!routerModule) {
- output.printError('Router module not available');
+ try {
+ const router = await getRouter();
+ router.reset();
+ output.printSuccess('Q-Learning router state has been reset');
+ return { success: true };
+ } catch (error) {
+ output.printError(error instanceof Error ? error.message : String(error));
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+// ============================================================================
+// Export/Import Subcommands
+// ============================================================================
+
+const exportCommand: Command = {
+ name: 'export',
+ description: 'Export Q-table for persistence',
+ options: [
+ {
+ name: 'file',
+ short: 'f',
+ description: 'Output file path (outputs to stdout if not specified)',
+ type: 'string',
+ },
+ ],
+ examples: [
+ { command: 'claude-flow route export', description: 'Export Q-table to stdout' },
+ { command: 'claude-flow route export -f qtable.json', description: 'Export to file' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const filePath = ctx.flags.file as string | undefined;
+
+ try {
+ const router = await getRouter();
+ const data = router.export();
+
+ if (filePath) {
+ const fs = await import('node:fs/promises');
+ await fs.writeFile(filePath, JSON.stringify(data, null, 2));
+ output.printSuccess(`Q-table exported to ${filePath}`);
+ } else {
+ output.printJson(data);
+ }
+
+ return { success: true, data };
+ } catch (error) {
+ output.printError(error instanceof Error ? error.message : String(error));
+ return { success: false, exitCode: 1 };
+ }
+ },
+};
+
+const importCommand: Command = {
+ name: 'import',
+ description: 'Import Q-table from file',
+ options: [
+ {
+ name: 'file',
+ short: 'f',
+ description: 'Input file path',
+ type: 'string',
+ required: true,
+ },
+ ],
+ examples: [
+ { command: 'claude-flow route import -f qtable.json', description: 'Import Q-table from file' },
+ ],
+ action: async (ctx: CommandContext): Promise<CommandResult> => {
+ const filePath = ctx.flags.file as string;
+
+ if (!filePath) {
+ output.printError('File path is required');
return { success: false, exitCode: 1 };
}
try {
- const router = await routerModule.getRouter();
- router.reset();
- output.printSuccess('Q-Learning router state has been reset');
+ const fs = await import('node:fs/promises');
+ const content = await fs.readFile(filePath, 'utf-8');
+ const data = JSON.parse(content);
+
+ const router = await getRouter();
+ router.import(data);
+
+ output.printSuccess(`Q-table imported from ${filePath}`);
+ output.writeln(output.dim(`Loaded ${Object.keys(data).length} state entries`));
+
return { success: true };
} catch (error) {
output.printError(error instanceof Error ? error.message : String(error));
@@ -515,7 +581,15 @@ const resetCommand: Command = {
export const routeCommand: Command = {
name: 'route',
description: 'Intelligent task-to-agent routing using Q-Learning',
- subcommands: [routeTaskCommand, listAgentsCommand, statsCommand, feedbackCommand, resetCommand],
+ subcommands: [
+ routeTaskCommand,
+ listAgentsCommand,
+ statsCommand,
+ feedbackCommand,
+ resetCommand,
+ exportCommand,
+ importCommand,
+ ],
options: [
{
name: 'q-learning',
@@ -540,8 +614,10 @@ export const routeCommand: Command = {
],
action: async (ctx: CommandContext): Promise<CommandResult> => {
// If task description provided directly, route it
- if (ctx.args.length > 0) {
- return routeTaskCommand.action!(ctx);
+ if (ctx.args.length > 0 && routeTaskCommand.action) {
+ const result = await routeTaskCommand.action(ctx);
+ if (result) return result;
+ return { success: true };
}
// Show help
@@ -561,12 +637,14 @@ export const routeCommand: Command = {
`${output.highlight('stats')} - Show router statistics`,
`${output.highlight('feedback')} - Provide routing feedback`,
`${output.highlight('reset')} - Reset router state`,
+ `${output.highlight('export')} - Export Q-table`,
+ `${output.highlight('import')} - Import Q-table`,
]);
output.writeln();
output.writeln(output.bold('How It Works:'));
output.printList([
- 'Analyzes task description using semantic embeddings',
+ 'Analyzes task description using hash-based state encoding',
'Uses Q-Learning to learn from routing outcomes',
'Epsilon-greedy exploration for continuous improvement',
'Provides confidence scores and alternatives',
@@ -574,13 +652,12 @@ export const routeCommand: Command = {
output.writeln();
// Show quick status
- const ruvectorModule = await getRuVectorModule();
- const status = ruvectorModule?.getStatus?.() ?? { available: false, backend: 'fallback' };
+ const ruvectorAvailable = await isRuvectorAvailable();
output.writeln(output.bold('Backend Status:'));
output.printList([
- `RuVector: ${status.available ? output.success('Available') : output.warning('Fallback mode')}`,
- `Backend: ${status.backend}`,
+ `RuVector: ${ruvectorAvailable ? output.success('Available') : output.warning('Fallback mode')}`,
+ `Backend: ${ruvectorAvailable ? 'ruvector-native' : 'JavaScript fallback'}`,
]);
output.writeln();
diff --git a/v3/@claude-flow/cli/src/ruvector/ast-analyzer.ts b/v3/@claude-flow/cli/src/ruvector/ast-analyzer.ts
index 8cbc76f7d5..aa966f5879 100644
--- a/v3/@claude-flow/cli/src/ruvector/ast-analyzer.ts
+++ b/v3/@claude-flow/cli/src/ruvector/ast-analyzer.ts
@@ -1,608 +1,309 @@
/**
- * AST Analyzer - Wrapper for ruvector's AST parsing capabilities
+ * AST Analyzer for Code Analysis
*
- * Provides code analysis features:
- * - Symbol extraction (functions, classes, variables)
- * - Cyclomatic complexity scoring
- * - Code structure analysis
- * - Graceful fallback when ruvector not installed
+ * Analyzes Abstract Syntax Trees for code understanding
+ * and intelligent routing decisions.
*
- * Created with ruv.io
+ * @module ast-analyzer
*/
-import * as fs from 'fs/promises';
-import * as path from 'path';
-
-// Type definitions matching ruvector's API
-export interface FunctionInfo {
- name: string;
- params: string[];
- returnType?: string;
- async: boolean;
- exported: boolean;
- startLine: number;
- endLine: number;
- complexity: number;
- calls: string[];
+export interface ASTAnalyzerConfig {
+ maxFileSize: number;
+ languages: string[];
+ includeComments: boolean;
+ extractTypes: boolean;
+ maxDepth: number;
}
-export interface ClassInfo {
+export interface ASTNode {
+ type: string;
name: string;
- extends?: string;
- implements: string[];
- methods: FunctionInfo[];
- properties: string[];
- exported: boolean;
startLine: number;
endLine: number;
+ children: ASTNode[];
+ metadata?: Record<string, unknown>;
}
-export interface ImportInfo {
- source: string;
- default?: string;
- named: string[];
- namespace?: string;
- type: 'esm' | 'commonjs' | 'dynamic';
-}
-
-export interface ExportInfo {
- name: string;
- type: 'default' | 'named' | 'all';
- source?: string;
-}
-
-export interface FileAnalysis {
- file: string;
+export interface ASTAnalysis {
+ filePath: string;
language: string;
- imports: ImportInfo[];
- exports: ExportInfo[];
- functions: FunctionInfo[];
- classes: ClassInfo[];
- variables: string[];
- types: string[];
- complexity: number;
- lines: number;
- parseTime: number;
-}
-
-export interface ComplexityResult {
- file: string;
- lines: number;
- nonEmptyLines: number;
- cyclomaticComplexity: number;
- functions: number;
- avgFunctionSize: number;
- maxFunctionComplexity?: number;
-}
-
-export interface ASTAnalyzerOptions {
- includeComplexity?: boolean;
- recursive?: boolean;
- extensions?: string[];
- maxFiles?: number;
-}
-
-// Check if ruvector is available
-let ruvectorModule: any = null;
-let ruvectorAvailable = false;
-
-async function loadRuvector(): Promise<boolean> {
- if (ruvectorModule !== null) {
- return ruvectorAvailable;
- }
-
- try {
- ruvectorModule = await import('ruvector');
- ruvectorAvailable = true;
- return true;
- } catch {
- ruvectorModule = {};
- ruvectorAvailable = false;
- return false;
- }
-}
-
-/**
- * Check if ruvector is available
- */
-export async function isRuvectorAvailable(): Promise<boolean> {
- return loadRuvector();
-}
-
-/**
- * Get complexity rating from score
- */
-export function getComplexityRating(complexity: number): 'low' | 'medium' | 'high' | 'critical' {
- if (complexity <= 10) return 'low';
- if (complexity <= 20) return 'medium';
- if (complexity <= 30) return 'high';
- return 'critical';
-}
-
-/**
- * Detect language from file extension
- */
-export function detectLanguage(file: string): string {
- const ext = path.extname(file).toLowerCase();
- const languageMap: Record<string, string> = {
- '.ts': 'typescript',
- '.tsx': 'typescript',
- '.js': 'javascript',
- '.jsx': 'javascript',
- '.mjs': 'javascript',
- '.cjs': 'javascript',
- '.py': 'python',
- '.rs': 'rust',
- '.go': 'go',
- '.java': 'java',
- '.c': 'c',
- '.cpp': 'cpp',
- '.h': 'c',
- '.hpp': 'cpp',
+ root: ASTNode;
+ functions: ASTNode[];
+ classes: ASTNode[];
+ imports: string[];
+ exports: string[];
+ complexity: {
+ cyclomatic: number;
+ cognitive: number;
+ loc: number;
+ commentDensity: number;
};
- return languageMap[ext] || 'unknown';
+ timestamp: number;
+ durationMs: number;
}
-/**
- * Analyze a single file using ruvector's AST parser
- */
-export async function analyzeFile(
- filePath: string,
- options: ASTAnalyzerOptions = {}
-): Promise<FileAnalysis | null> {
- const available = await loadRuvector();
+const DEFAULT_CONFIG: ASTAnalyzerConfig = {
+ maxFileSize: 1024 * 1024,
+ languages: ['typescript', 'javascript', 'python', 'rust', 'go'],
+ includeComments: true,
+ extractTypes: true,
+ maxDepth: 20,
+};
- if (available && ruvectorModule.CodeParser) {
- try {
- const parser = ruvectorModule.getCodeParser?.() ?? new ruvectorModule.CodeParser();
- await parser.init();
- return await parser.analyze(filePath);
- } catch (error) {
- // Fall through to fallback
- }
- }
+const LANGUAGE_PATTERNS: Record<string, RegExp[]> = {
+ typescript: [/\.tsx?$/, /^import\s+.*from\s+['"]/, /:\s*(string|number|boolean|void)/],
+ javascript: [/\.jsx?$/, /^(const|let|var)\s+\w+\s*=/, /module\.exports/],
+ python: [/\.py$/, /^(def|class|import|from)\s+/, /^#!/],
+ rust: [/\.rs$/, /^(fn|struct|impl|use)\s+/, /^(pub\s+)?mod\s+/],
+ go: [/\.go$/, /^package\s+/, /^func\s+/],
+};
- // Fallback: regex-based analysis
- return await analyzeFileWithFallback(filePath);
-}
+export class ASTAnalyzer {
+ private config: ASTAnalyzerConfig;
+ private ruvectorEngine: unknown = null;
+ private useNative = false;
+ private analysisCache: Map<string, ASTAnalysis> = new Map();
-/**
- * Analyze complexity of a single file
- */
-export async function analyzeComplexity(
- filePath: string
-): Promise<ComplexityResult | null> {
- const available = await loadRuvector();
+ constructor(config: Partial<ASTAnalyzerConfig> = {}) {
+ this.config = { ...DEFAULT_CONFIG, ...config };
+ }
- if (available && ruvectorModule.analyzeFile) {
+ async initialize(): Promise<void> {
try {
- return ruvectorModule.analyzeFile(filePath);
+ const ruvector = await import('@ruvector/ast');
+ this.ruvectorEngine = (ruvector as any).createASTAnalyzer?.(this.config);
+ this.useNative = !!this.ruvectorEngine;
} catch {
- // Fall through to fallback
+ this.useNative = false;
}
}
- // Fallback: simple complexity analysis
- return await analyzeComplexityWithFallback(filePath);
-}
-
-/**
- * Analyze multiple files
- */
-export async function analyzeFiles(
- files: string[],
- options: ASTAnalyzerOptions = {}
-): Promise<FileAnalysis[]> {
- const maxFiles = options.maxFiles ?? 100;
- const filesToAnalyze = files.slice(0, maxFiles);
- const results: FileAnalysis[] = [];
-
- for (const file of filesToAnalyze) {
- try {
- const result = await analyzeFile(file, options);
- if (result) {
- results.push(result);
- }
- } catch {
- // Skip files that fail to analyze
+ analyze(code: string, filePath: string = 'unknown'): ASTAnalysis {
+ const startTime = performance.now();
+ if (code.length > this.config.maxFileSize) {
+ throw new Error(`File too large: ${code.length} bytes exceeds ${this.config.maxFileSize}`);
}
+ const cacheKey = this.getCacheKey(code, filePath);
+ const cached = this.analysisCache.get(cacheKey);
+ if (cached) return cached;
+ const language = this.detectLanguage(code, filePath);
+ const root = this.parseAST(code, language);
+ const functions = this.extractFunctions(root);
+ const classes = this.extractClasses(root);
+ const imports = this.extractImports(code, language);
+ const exports = this.extractExports(code, language);
+ const complexity = this.calculateComplexity(code, root);
+ const durationMs = performance.now() - startTime;
+ const analysis: ASTAnalysis = {
+ filePath, language, root, functions, classes, imports, exports,
+ complexity, timestamp: Date.now(), durationMs,
+ };
+ this.analysisCache.set(cacheKey, analysis);
+ return analysis;
}
- return results;
-}
-
-/**
- * Analyze complexity for multiple files
- */
-export async function analyzeFilesComplexity(
- files: string[],
- options: ASTAnalyzerOptions = {}
-): Promise<ComplexityResult[]> {
- const maxFiles = options.maxFiles ?? 100;
- const filesToAnalyze = files.slice(0, maxFiles);
- const results: ComplexityResult[] = [];
-
- for (const file of filesToAnalyze) {
- try {
- const result = await analyzeComplexity(file);
- if (result) {
- results.push(result);
- }
- } catch {
- // Skip files that fail to analyze
+ getFunctionAtLine(analysis: ASTAnalysis, line: number): ASTNode | null {
+ for (const func of analysis.functions) {
+ if (line >= func.startLine && line <= func.endLine) return func;
}
+ return null;
}
- return results;
-}
-
-/**
- * Get all symbols from a file
- */
-export async function getSymbols(filePath: string): Promise<string[]> {
- const available = await loadRuvector();
-
- if (available && ruvectorModule.CodeParser) {
- try {
- const parser = ruvectorModule.getCodeParser?.() ?? new ruvectorModule.CodeParser();
- await parser.init();
- return await parser.getSymbols(filePath);
- } catch {
- // Fall through to fallback
+ getClassAtLine(analysis: ASTAnalysis, line: number): ASTNode | null {
+ for (const cls of analysis.classes) {
+ if (line >= cls.startLine && line <= cls.endLine) return cls;
}
+ return null;
}
- // Fallback: extract symbols with regex
- const analysis = await analyzeFileWithFallback(filePath);
- if (!analysis) return [];
-
- return [
- ...analysis.functions.map(f => f.name),
- ...analysis.classes.map(c => c.name),
- ...analysis.variables,
- ...analysis.types,
- ];
-}
-
-/**
- * Scan directory for analyzable files
- */
-export async function scanDirectory(
- dirPath: string,
- options: ASTAnalyzerOptions = {}
-): Promise<string[]> {
- const extensions = options.extensions ?? ['.ts', '.tsx', '.js', '.jsx', '.py', '.rs', '.go'];
- const files: string[] = [];
+ getSymbols(analysis: ASTAnalysis): string[] {
+ const symbols: string[] = [];
+ for (const func of analysis.functions) symbols.push(func.name);
+ for (const cls of analysis.classes) symbols.push(cls.name);
+ return symbols;
+ }
- async function scan(dir: string, depth: number = 0): Promise<void> {
- if (depth > 10) return; // Max depth protection
+ getStats(): Record<string, number> {
+ return { cacheSize: this.analysisCache.size, useNative: this.useNative ? 1 : 0 };
+ }
- try {
- const entries = await fs.readdir(dir, { withFileTypes: true });
+ clearCache(): void { this.analysisCache.clear(); }
- for (const entry of entries) {
- const fullPath = path.join(dir, entry.name);
+ private getCacheKey(code: string, filePath: string): string {
+ let hash = 0;
+ const str = filePath + code.substring(0, 1000);
+ for (let i = 0; i < str.length; i++) {
+ const char = str.charCodeAt(i);
+ hash = ((hash << 5) - hash) + char;
+ hash = hash & hash;
+ }
+ return `ast_${hash}_${code.length}`;
+ }
- // Skip common directories
- if (entry.isDirectory()) {
- if (!['node_modules', '.git', 'dist', 'build', '.next', '__pycache__'].includes(entry.name)) {
- if (options.recursive !== false) {
- await scan(fullPath, depth + 1);
- }
- }
- } else if (entry.isFile()) {
- const ext = path.extname(entry.name).toLowerCase();
- if (extensions.includes(ext)) {
- files.push(fullPath);
- }
- }
+ private detectLanguage(code: string, filePath: string): string {
+ for (const [lang, patterns] of Object.entries(LANGUAGE_PATTERNS)) {
+ for (const pattern of patterns) {
+ if (pattern.test(filePath) || pattern.test(code)) return lang;
}
- } catch {
- // Skip inaccessible directories
}
+ return 'unknown';
}
- await scan(dirPath);
- return files;
-}
-
-// ============================================
-// Fallback Implementations
-// ============================================
-
-/**
- * Fallback file analysis using regex
- */
-async function analyzeFileWithFallback(filePath: string): Promise<FileAnalysis | null> {
- const startTime = Date.now();
-
- try {
- const content = await fs.readFile(filePath, 'utf-8');
- const lines = content.split('\n');
- const language = detectLanguage(filePath);
+ private parseAST(code: string, language: string): ASTNode {
+ const lines = code.split('\n');
+ const root: ASTNode = { type: 'program', name: 'root', startLine: 1, endLine: lines.length, children: [] };
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const lineNum = i + 1;
+ const funcMatch = this.matchFunction(line, language);
+ if (funcMatch) {
+ const funcNode: ASTNode = {
+ type: 'function', name: funcMatch.name, startLine: lineNum,
+ endLine: lineNum + this.findBlockEnd(lines, i), children: [],
+ metadata: { params: funcMatch.params },
+ };
+ root.children.push(funcNode);
+ continue;
+ }
+ const classMatch = this.matchClass(line, language);
+ if (classMatch) {
+ const classNode: ASTNode = {
+ type: 'class', name: classMatch.name, startLine: lineNum,
+ endLine: lineNum + this.findBlockEnd(lines, i), children: [],
+ metadata: { extends: classMatch.extends },
+ };
+ root.children.push(classNode);
+ }
+ }
+ return root;
+ }
- const analysis: FileAnalysis = {
- file: filePath,
- language,
- imports: extractImports(content, language),
- exports: extractExports(content, language),
- functions: extractFunctions(content, language),
- classes: extractClasses(content, language),
- variables: extractVariables(content, language),
- types: extractTypes(content, language),
- complexity: calculateComplexity(content),
- lines: lines.length,
- parseTime: Date.now() - startTime,
+ private matchFunction(line: string, language: string): { name: string; params: string } | null {
+ const patterns: Record<string, RegExp> = {
+ typescript: /(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\(([^)]*)\)/,
+ javascript: /(?:export\s+)?(?:async\s+)?function\s+(\w+)\s*\(([^)]*)\)/,
+ python: /def\s+(\w+)\s*\(([^)]*)\)/,
+ rust: /(?:pub\s+)?(?:async\s+)?fn\s+(\w+)\s*\(([^)]*)\)/,
+ go: /func\s+(?:\([^)]*\)\s+)?(\w+)\s*\(([^)]*)\)/,
};
-
- return analysis;
- } catch {
+ const pattern = patterns[language];
+ if (!pattern) return null;
+ const match = line.match(pattern);
+ if (match) return { name: match[1], params: match[2] || '' };
+ const arrowMatch = line.match(/(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>/);
+ if (arrowMatch) return { name: arrowMatch[1], params: '' };
+ const methodMatch = line.match(/^\s*(?:async\s+)?(\w+)\s*\([^)]*\)\s*(?::\s*\w+)?\s*\{/);
+ if (methodMatch && methodMatch[1] !== 'if' && methodMatch[1] !== 'while' && methodMatch[1] !== 'for') {
+ return { name: methodMatch[1], params: '' };
+ }
return null;
}
-}
-/**
- * Fallback complexity analysis
- */
-async function analyzeComplexityWithFallback(filePath: string): Promise<ComplexityResult | null> {
- try {
- const content = await fs.readFile(filePath, 'utf-8');
- const lines = content.split('\n');
- const nonEmptyLines = lines.filter(l => l.trim().length > 0).length;
-
- const functionMatches = content.match(/function\s+\w+|(?:async\s+)?(?:const|let|var)\s+\w+\s*=\s*(?:async\s+)?\(/g);
- const functions = functionMatches?.length ?? 0;
-
- return {
- file: filePath,
- lines: lines.length,
- nonEmptyLines,
- cyclomaticComplexity: calculateComplexity(content),
- functions,
- avgFunctionSize: functions > 0 ? Math.round(nonEmptyLines / functions) : nonEmptyLines,
- maxFunctionComplexity: undefined, // Not available in fallback
+ private matchClass(line: string, language: string): { name: string; extends?: string } | null {
+ const patterns: Record<string, RegExp> = {
+ typescript: /(?:export\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?/,
+ javascript: /(?:export\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?/,
+ python: /class\s+(\w+)(?:\((\w+)\))?/,
+ rust: /(?:pub\s+)?struct\s+(\w+)/,
+ go: /type\s+(\w+)\s+struct/,
};
- } catch {
+ const pattern = patterns[language];
+ if (!pattern) return null;
+ const match = line.match(pattern);
+ if (match) return { name: match[1], extends: match[2] };
return null;
}
-}
-function extractImports(content: string, language: string): ImportInfo[] {
- const imports: ImportInfo[] = [];
-
- if (language === 'typescript' || language === 'javascript') {
- // ES imports
- const esmRegex = /import\s+(?:(?:(\w+)\s*,?\s*)?(?:\{([^}]+)\})?(?:\*\s+as\s+(\w+))?\s+from\s+)?['"]([^'"]+)['"]/g;
- let match;
- while ((match = esmRegex.exec(content)) !== null) {
- imports.push({
- source: match[4],
- default: match[1],
- named: match[2] ? match[2].split(',').map(s => s.trim().split(/\s+as\s+/)[0]) : [],
- namespace: match[3],
- type: 'esm',
- });
- }
-
- // CommonJS require
- const cjsRegex = /(?:const|let|var)\s+(?:(\w+)|(\{[^}]+\}))\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
- while ((match = cjsRegex.exec(content)) !== null) {
- imports.push({
- source: match[3],
- default: match[1],
- named: match[2] ? match[2].replace(/[{}]/g, '').split(',').map(s => s.trim()) : [],
- type: 'commonjs',
- });
- }
- } else if (language === 'python') {
- // Python imports
- const pyImportRegex = /(?:from\s+(\S+)\s+)?import\s+([^#\n]+)/g;
- let match;
- while ((match = pyImportRegex.exec(content)) !== null) {
- imports.push({
- source: match[1] || match[2].split(',')[0].trim(),
- named: match[2].split(',').map(s => s.trim().split(/\s+as\s+/)[0]),
- type: 'esm',
- });
+ private findBlockEnd(lines: string[], startIdx: number): number {
+ let depth = 0;
+ let inBlock = false;
+ for (let i = startIdx; i < lines.length; i++) {
+ const line = lines[i];
+ const opens = (line.match(/[\{]/g) || []).length;
+ const closes = (line.match(/[\}]/g) || []).length;
+ if (opens > 0) inBlock = true;
+ depth += opens - closes;
+ if (inBlock && depth <= 0) return i - startIdx;
}
+ return Math.min(50, lines.length - startIdx);
}
- return imports;
-}
-
-function extractExports(content: string, language: string): ExportInfo[] {
- const exports: ExportInfo[] = [];
-
- if (language === 'typescript' || language === 'javascript') {
- // Export default
- const defaultRegex = /export\s+default\s+(?:class|function|const|let|var)?\s*(\w+)?/g;
- let match;
- while ((match = defaultRegex.exec(content)) !== null) {
- exports.push({ name: match[1] || 'default', type: 'default' });
- }
-
- // Named exports
- const namedRegex = /export\s+(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/g;
- while ((match = namedRegex.exec(content)) !== null) {
- exports.push({ name: match[1], type: 'named' });
- }
-
- // Export all
- const allRegex = /export\s*\*\s*from\s*['"]([^'"]+)['"]/g;
- while ((match = allRegex.exec(content)) !== null) {
- exports.push({ name: '*', type: 'all', source: match[1] });
- }
+ private extractFunctions(root: ASTNode): ASTNode[] {
+ const functions: ASTNode[] = [];
+ const visit = (node: ASTNode) => {
+ if (node.type === 'function') functions.push(node);
+ for (const child of node.children) visit(child);
+ };
+ visit(root);
+ return functions;
}
- return exports;
-}
-
-function extractFunctions(content: string, language: string): FunctionInfo[] {
- const functions: FunctionInfo[] = [];
- const lines = content.split('\n');
-
- if (language === 'typescript' || language === 'javascript') {
- // Function declarations and expressions
- const funcRegex = /(?:export\s+)?(async\s+)?(?:function\s+(\w+)|(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:function|\([^)]*\)\s*=>|\w+\s*=>))/g;
- let match;
- while ((match = funcRegex.exec(content)) !== null) {
- const name = match[2] || match[3];
- if (name) {
- const lineNum = content.substring(0, match.index).split('\n').length;
- functions.push({
- name,
- params: [],
- async: !!match[1],
- exported: content.substring(Math.max(0, match.index - 10), match.index).includes('export'),
- startLine: lineNum,
- endLine: lineNum + 10, // Approximate
- complexity: 1,
- calls: [],
- });
- }
- }
- } else if (language === 'python') {
- const pyFuncRegex = /(async\s+)?def\s+(\w+)\s*\(/g;
- let match;
- while ((match = pyFuncRegex.exec(content)) !== null) {
- const lineNum = content.substring(0, match.index).split('\n').length;
- functions.push({
- name: match[2],
- params: [],
- async: !!match[1],
- exported: true,
- startLine: lineNum,
- endLine: lineNum + 10,
- complexity: 1,
- calls: [],
- });
- }
+ private extractClasses(root: ASTNode): ASTNode[] {
+ const classes: ASTNode[] = [];
+ const visit = (node: ASTNode) => {
+ if (node.type === 'class') classes.push(node);
+ for (const child of node.children) visit(child);
+ };
+ visit(root);
+ return classes;
}
- return functions;
-}
-
-function extractClasses(content: string, language: string): ClassInfo[] {
- const classes: ClassInfo[] = [];
-
- if (language === 'typescript' || language === 'javascript') {
- const classRegex = /(?:export\s+)?class\s+(\w+)(?:\s+extends\s+(\w+))?(?:\s+implements\s+([^{]+))?/g;
- let match;
- while ((match = classRegex.exec(content)) !== null) {
- const lineNum = content.substring(0, match.index).split('\n').length;
- classes.push({
- name: match[1],
- extends: match[2],
- implements: match[3] ? match[3].split(',').map(s => s.trim()) : [],
- methods: [],
- properties: [],
- exported: content.substring(Math.max(0, match.index - 10), match.index).includes('export'),
- startLine: lineNum,
- endLine: lineNum + 20,
- });
- }
- } else if (language === 'python') {
- const pyClassRegex = /class\s+(\w+)(?:\s*\(([^)]*)\))?/g;
- let match;
- while ((match = pyClassRegex.exec(content)) !== null) {
- const lineNum = content.substring(0, match.index).split('\n').length;
- classes.push({
- name: match[1],
- extends: match[2]?.split(',')[0]?.trim(),
- implements: [],
- methods: [],
- properties: [],
- exported: true,
- startLine: lineNum,
- endLine: lineNum + 20,
- });
+ private extractImports(code: string, language: string): string[] {
+ const imports: string[] = [];
+ const lines = code.split('\n');
+ const patterns: Record<string, RegExp> = {
+ typescript: /import\s+(?:.*\s+from\s+)?['"]([^'"]+)['"]/,
+ javascript: /(?:import\s+.*from\s+|require\s*\(\s*)['"]([^'"]+)['"]/,
+ python: /(?:from\s+(\S+)\s+import|import\s+(\S+))/,
+ rust: /use\s+(\S+)/,
+ go: /import\s+(?:\(\s*)?["']([^"']+)["']/,
+ };
+ const pattern = patterns[language];
+ if (!pattern) return imports;
+ for (const line of lines) {
+ const match = line.match(pattern);
+ if (match) imports.push(match[1] || match[2]);
}
+ return imports;
}
- return classes;
-}
-
-function extractVariables(content: string, language: string): string[] {
- const variables: string[] = [];
-
- if (language === 'typescript' || language === 'javascript') {
- // Top-level const/let/var (not in functions)
- const varRegex = /^(?:export\s+)?(?:const|let|var)\s+(\w+)\s*[=:]/gm;
- let match;
- while ((match = varRegex.exec(content)) !== null) {
- // Skip if it looks like a function
- const afterMatch = content.substring(match.index, match.index + 200);
- if (!afterMatch.includes('=>') && !afterMatch.includes('function')) {
- variables.push(match[1]);
+ private extractExports(code: string, language: string): string[] {
+ const exports: string[] = [];
+ const lines = code.split('\n');
+ for (const line of lines) {
+ const exportMatch = line.match(/export\s+(?:default\s+)?(?:const|let|var|function|class|interface|type|enum)\s+(\w+)/);
+ if (exportMatch) exports.push(exportMatch[1]);
+ const namedExportMatch = line.match(/export\s*\{\s*([^}]+)\s*\}/);
+ if (namedExportMatch) {
+ const names = namedExportMatch[1].split(',').map(n => n.trim().split(/\s+as\s+/)[0]);
+ exports.push(...names);
}
}
+ return exports;
}
- return variables;
-}
-
-function extractTypes(content: string, language: string): string[] {
- const types: string[] = [];
-
- if (language === 'typescript') {
- // Interfaces
- const interfaceRegex = /(?:export\s+)?interface\s+(\w+)/g;
- let match;
- while ((match = interfaceRegex.exec(content)) !== null) {
- types.push(match[1]);
- }
-
- // Type aliases
- const typeRegex = /(?:export\s+)?type\s+(\w+)\s*[=<]/g;
- while ((match = typeRegex.exec(content)) !== null) {
- types.push(match[1]);
- }
-
- // Enums
- const enumRegex = /(?:export\s+)?(?:const\s+)?enum\s+(\w+)/g;
- while ((match = enumRegex.exec(content)) !== null) {
- types.push(match[1]);
+ private calculateComplexity(code: string, root: ASTNode): ASTAnalysis['complexity'] {
+ const lines = code.split('\n');
+ const nonEmptyLines = lines.filter(l => l.trim().length > 0);
+ const commentLines = lines.filter(l => /^\s*(\/\/|\/\*|\*|#)/.test(l));
+ const decisionPoints = (code.match(/\b(if|else|for|while|switch|case|catch|&&|\|\||\?)\b/g) || []).length;
+ const cyclomatic = decisionPoints + 1;
+ let cognitive = 0;
+ let nestingLevel = 0;
+ for (const line of lines) {
+ const opens = (line.match(/[\{]/g) || []).length;
+ const closes = (line.match(/[\}]/g) || []).length;
+ if (/\b(if|for|while|switch)\b/.test(line)) cognitive += 1 + nestingLevel;
+ nestingLevel += opens - closes;
+ nestingLevel = Math.max(0, nestingLevel);
}
+ return {
+ cyclomatic, cognitive, loc: nonEmptyLines.length,
+ commentDensity: lines.length > 0 ? commentLines.length / lines.length : 0,
+ };
}
-
- return types;
}
-function calculateComplexity(content: string): number {
- // Simple cyclomatic complexity calculation
- const conditions = [
- /\bif\s*\(/g,
- /\belse\s+if\s*\(/g,
- /\bfor\s*\(/g,
- /\bwhile\s*\(/g,
- /\bcase\s+/g,
- /\bcatch\s*\(/g,
- /\?\s*[^:]/g, // Ternary
- /&&/g,
- /\|\|/g,
- /\?\?/g, // Nullish coalescing
- ];
-
- let complexity = 1; // Base complexity
-
- for (const pattern of conditions) {
- const matches = content.match(pattern);
- if (matches) {
- complexity += matches.length;
- }
- }
-
- return complexity;
+export function createASTAnalyzer(config?: Partial<ASTAnalyzerConfig>): ASTAnalyzer {
+ return new ASTAnalyzer(config);
}
-
-export default {
- isRuvectorAvailable,
- analyzeFile,
- analyzeFiles,
- analyzeComplexity,
- analyzeFilesComplexity,
- getSymbols,
- scanDirectory,
- getComplexityRating,
- detectLanguage,
-};
diff --git a/v3/@claude-flow/cli/src/ruvector/coverage-router.ts b/v3/@claude-flow/cli/src/ruvector/coverage-router.ts
index e4a2350a3d..a774569da3 100644
--- a/v3/@claude-flow/cli/src/ruvector/coverage-router.ts
+++ b/v3/@claude-flow/cli/src/ruvector/coverage-router.ts
@@ -1,985 +1,273 @@
/**
- * Coverage-Aware Routing for @claude-flow/cli
- *
- * Integrates with ruvector's hooks_coverage_route and hooks_coverage_suggest
- * to route tasks to agents based on test coverage gaps.
- *
- * Supports coverage formats:
- * - lcov (lcov.info)
- * - istanbul (coverage-summary.json, coverage-final.json)
- * - c8 (coverage/coverage-summary.json)
+ * Coverage Router for Test Routing
*/
-import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
-import { join, resolve, relative, dirname, basename, extname } from 'path';
-
-// ============================================================================
-// Types
-// ============================================================================
+export interface CoverageRouterConfig {
+ minCoverage: number;
+ targetCoverage: number;
+ incremental: boolean;
+ coverageTypes: ('line' | 'branch' | 'function' | 'statement')[];
+}
-export interface CoverageData {
- /** File path relative to project root */
- filePath: string;
- /** Line coverage percentage (0-100) */
+export interface FileCoverage {
+ path: string;
lineCoverage: number;
- /** Branch coverage percentage (0-100) */
branchCoverage: number;
- /** Function coverage percentage (0-100) */
functionCoverage: number;
- /** Statement coverage percentage (0-100) */
statementCoverage: number;
- /** Uncovered line numbers */
uncoveredLines: number[];
- /** Uncovered branch locations */
- uncoveredBranches: UncoveredBranch[];
- /** Uncovered function names */
- uncoveredFunctions: string[];
- /** Total lines in file */
totalLines: number;
- /** Lines that are covered */
coveredLines: number;
}
-export interface UncoveredBranch {
- line: number;
- column?: number;
- type: 'if' | 'else' | 'case' | 'ternary' | 'logical' | 'unknown';
-}
-
-export interface CoverageSummary {
- totalFiles: number;
- overallLineCoverage: number;
- overallBranchCoverage: number;
- overallFunctionCoverage: number;
- overallStatementCoverage: number;
- filesBelowThreshold: number;
- coverageThreshold: number;
-}
-
-export interface CoverageGap {
- filePath: string;
- coveragePercent: number;
- gapType: 'critical' | 'high' | 'medium' | 'low';
- complexity: number;
- priority: number;
- suggestedAgents: string[];
- uncoveredLines: number[];
- reason: string;
+export interface CoverageReport {
+ overall: number;
+ byType: { line: number; branch: number; function: number; statement: number };
+ byFile: FileCoverage[];
+ lowestCoverage: FileCoverage[];
+ highestCoverage: FileCoverage[];
+ uncoveredCritical: string[];
+ timestamp: number;
}
export interface CoverageRouteResult {
- success: boolean;
- task: string;
- coverageAware: boolean;
- gaps: CoverageGap[];
- routing: {
- primaryAgent: string;
- confidence: number;
- reason: string;
- coverageImpact: string;
- };
- suggestions: string[];
- metrics: {
- filesAnalyzed: number;
- totalGaps: number;
- criticalGaps: number;
- avgCoverage: number;
- };
-}
-
-export interface CoverageSuggestResult {
- success: boolean;
- path: string;
- suggestions: CoverageGap[];
- summary: CoverageSummary;
- prioritizedFiles: string[];
- ruvectorAvailable: boolean;
-}
-
-export interface CoverageGapsResult {
- success: boolean;
- gaps: CoverageGap[];
- summary: CoverageSummary;
- agentAssignments: Record<string, string[]>;
- ruvectorAvailable: boolean;
+ action: 'add-tests' | 'review-coverage' | 'skip' | 'prioritize';
+ priority: number;
+ targetFiles: string[];
+ testTypes: ('unit' | 'integration' | 'e2e')[];
+ gaps: Array<{ file: string; currentCoverage: number; targetCoverage: number; gap: number; suggestedTests: string[] }>;
+ estimatedEffort: number;
+ impactScore: number;
}
-// ============================================================================
-// RuVector Integration (Graceful Fallback)
-// ============================================================================
-
-let ruvectorAvailable: boolean | null = null;
+const DEFAULT_CONFIG: CoverageRouterConfig = {
+ minCoverage: 70,
+ targetCoverage: 85,
+ incremental: true,
+ coverageTypes: ['line', 'branch', 'function', 'statement'],
+};
-interface RuVectorModule {
- hooks_coverage_route?: (task: string, coverageData: CoverageData[]) => Promise<unknown>;
- hooks_coverage_suggest?: (path: string, coverageData: CoverageData[]) => Promise<unknown>;
-}
+export class CoverageRouter {
+ private config: CoverageRouterConfig;
+ private ruvectorEngine: unknown = null;
+ private useNative = false;
+ private coverageHistory: CoverageReport[] = [];
-/**
- * Check if ruvector is available
- */
-async function checkRuvectorAvailable(): Promise<boolean> {
- if (ruvectorAvailable !== null) {
- return ruvectorAvailable;
+ constructor(config: Partial<CoverageRouterConfig> = {}) {
+ this.config = { ...DEFAULT_CONFIG, ...config };
}
- try {
- // Try to dynamically import ruvector
- const ruvector = await import('ruvector').catch(() => null) as RuVectorModule | null;
- ruvectorAvailable = ruvector !== null &&
- typeof ruvector.hooks_coverage_route === 'function' &&
- typeof ruvector.hooks_coverage_suggest === 'function';
- } catch {
- ruvectorAvailable = false;
+ async initialize(): Promise<void> {
+ try {
+ const ruvector = await import('@ruvector/coverage');
+ this.ruvectorEngine = (ruvector as any).createCoverageRouter?.(this.config);
+ this.useNative = !!this.ruvectorEngine;
+ } catch { this.useNative = false; }
}
- return ruvectorAvailable;
-}
-
-/**
- * Call ruvector's hooks_coverage_route if available
- */
-async function callRuvectorRoute(
- task: string,
- coverageData: CoverageData[]
-): Promise<unknown | null> {
- if (!(await checkRuvectorAvailable())) {
- return null;
- }
-
- try {
- const ruvector = await import('ruvector') as RuVectorModule;
- if (ruvector.hooks_coverage_route) {
- return await ruvector.hooks_coverage_route(task, coverageData);
+ parseCoverage(data: unknown, format: 'lcov' | 'istanbul' | 'cobertura' | 'json' = 'json'): CoverageReport {
+ switch (format) {
+ case 'lcov': return this.parseLcov(data as string);
+ case 'istanbul': return this.parseIstanbul(data as Record<string, unknown>);
+ case 'cobertura': return this.parseCobertura(data as string);
+ default: return this.parseJson(data as Record<string, unknown>);
}
- } catch {
- // Graceful fallback
}
- return null;
-}
-/**
- * Call ruvector's hooks_coverage_suggest if available
- */
-async function callRuvectorSuggest(
- path: string,
- coverageData: CoverageData[]
-): Promise<unknown | null> {
- if (!(await checkRuvectorAvailable())) {
- return null;
+ route(coverage: CoverageReport, changedFiles?: string[]): CoverageRouteResult {
+ const gaps = this.calculateGaps(coverage);
+ const targetFiles = this.prioritizeFiles(coverage, changedFiles);
+ const action = this.determineAction(coverage, gaps);
+ const priority = this.calculatePriority(coverage, changedFiles);
+ const testTypes = this.recommendTestTypes(gaps);
+ const estimatedEffort = this.estimateEffort(gaps);
+ const impactScore = this.calculateImpact(coverage, targetFiles);
+ return { action, priority, targetFiles, testTypes, gaps, estimatedEffort, impactScore };
}
- try {
- const ruvector = await import('ruvector') as RuVectorModule;
- if (ruvector.hooks_coverage_suggest) {
- return await ruvector.hooks_coverage_suggest(path, coverageData);
- }
- } catch {
- // Graceful fallback
+ getTrend(): { direction: 'up' | 'down' | 'stable'; change: number } {
+ if (this.coverageHistory.length < 2) return { direction: 'stable', change: 0 };
+ const recent = this.coverageHistory[this.coverageHistory.length - 1];
+ const previous = this.coverageHistory[this.coverageHistory.length - 2];
+ const change = recent.overall - previous.overall;
+ return { direction: change > 0.5 ? 'up' : change < -0.5 ? 'down' : 'stable', change };
}
- return null;
-}
-
-// ============================================================================
-// Coverage Report Parsing
-// ============================================================================
-
-/**
- * Find coverage report files in project
- */
-export function findCoverageReports(projectRoot: string): {
- type: 'lcov' | 'istanbul' | 'c8' | 'unknown';
- path: string;
-}[] {
- const reports: { type: 'lcov' | 'istanbul' | 'c8' | 'unknown'; path: string }[] = [];
- const coverageDir = join(projectRoot, 'coverage');
- // Check for lcov.info
- const lcovPaths = [
- join(projectRoot, 'coverage', 'lcov.info'),
- join(projectRoot, 'lcov.info'),
- join(projectRoot, 'coverage', 'lcov-report', 'lcov.info'),
- ];
-
- for (const lcovPath of lcovPaths) {
- if (existsSync(lcovPath)) {
- reports.push({ type: 'lcov', path: lcovPath });
- }
+ addToHistory(report: CoverageReport): void {
+ this.coverageHistory.push(report);
+ if (this.coverageHistory.length > 10) this.coverageHistory.shift();
}
- // Check for istanbul/c8 coverage-summary.json
- const summaryPaths = [
- join(coverageDir, 'coverage-summary.json'),
- join(coverageDir, 'coverage-final.json'),
- join(projectRoot, '.nyc_output', 'coverage-summary.json'),
- ];
-
- for (const summaryPath of summaryPaths) {
- if (existsSync(summaryPath)) {
- const type = summaryPath.includes('.nyc_output') ? 'istanbul' : 'c8';
- reports.push({ type, path: summaryPath });
- }
+ getStats(): Record<string, number | boolean> {
+ return { useNative: this.useNative, historySize: this.coverageHistory.length, minCoverage: this.config.minCoverage, targetCoverage: this.config.targetCoverage };
}
- return reports;
-}
-
-/**
- * Parse LCOV format coverage report
- */
-export function parseLcov(lcovContent: string): CoverageData[] {
- const files: CoverageData[] = [];
- const records = lcovContent.split('end_of_record');
-
- for (const record of records) {
- if (!record.trim()) continue;
-
- const lines = record.split('\n').map(l => l.trim()).filter(Boolean);
- const sfLine = lines.find(l => l.startsWith('SF:'));
- if (!sfLine) continue;
-
- const filePath = sfLine.substring(3);
- const data: CoverageData = {
- filePath,
- lineCoverage: 0,
- branchCoverage: 0,
- functionCoverage: 0,
- statementCoverage: 0,
- uncoveredLines: [],
- uncoveredBranches: [],
- uncoveredFunctions: [],
- totalLines: 0,
- coveredLines: 0,
- };
-
- let linesFound = 0;
- let linesHit = 0;
- let branchesFound = 0;
- let branchesHit = 0;
- let functionsFound = 0;
- let functionsHit = 0;
-
+ private parseLcov(data: string): CoverageReport {
+ const files: FileCoverage[] = [];
+ let currentFile: Partial<FileCoverage> | null = null;
+ const lines = data.split('\n');
for (const line of lines) {
- // Line coverage: DA:line_number,hit_count
- if (line.startsWith('DA:')) {
- const [lineNum, hitCount] = line.substring(3).split(',').map(Number);
- linesFound++;
- if (hitCount > 0) {
- linesHit++;
- } else {
- data.uncoveredLines.push(lineNum);
- }
- }
-
- // Branch coverage: BRDA:line_number,block_number,branch_number,hit_count
- if (line.startsWith('BRDA:')) {
- const parts = line.substring(5).split(',');
- const lineNum = parseInt(parts[0], 10);
- const hitCount = parts[3] === '-' ? 0 : parseInt(parts[3], 10);
- branchesFound++;
- if (hitCount > 0) {
- branchesHit++;
- } else {
- data.uncoveredBranches.push({
- line: lineNum,
- type: 'unknown',
- });
- }
- }
-
- // Function coverage: FNDA:hit_count,function_name
- if (line.startsWith('FNDA:')) {
- const [hitCount, funcName] = line.substring(5).split(',');
- functionsFound++;
- if (parseInt(hitCount, 10) > 0) {
- functionsHit++;
- } else {
- data.uncoveredFunctions.push(funcName);
- }
- }
-
- // Summary lines
- if (line.startsWith('LF:')) {
- data.totalLines = parseInt(line.substring(3), 10);
- }
- if (line.startsWith('LH:')) {
- data.coveredLines = parseInt(line.substring(3), 10);
- }
+ if (line.startsWith('SF:')) {
+ if (currentFile?.path) files.push(this.finalizeFileCoverage(currentFile));
+ currentFile = { path: line.substring(3), uncoveredLines: [], totalLines: 0, coveredLines: 0 };
+ } else if (line.startsWith('LF:')) { if (currentFile) currentFile.totalLines = parseInt(line.substring(3), 10); }
+ else if (line.startsWith('LH:')) { if (currentFile) currentFile.coveredLines = parseInt(line.substring(3), 10); }
+ else if (line.startsWith('DA:')) { const [lineNum, hits] = line.substring(3).split(',').map(Number); if (currentFile && hits === 0) currentFile.uncoveredLines?.push(lineNum); }
+ else if (line === 'end_of_record') { if (currentFile?.path) files.push(this.finalizeFileCoverage(currentFile)); currentFile = null; }
}
-
- // Calculate percentages
- data.lineCoverage = linesFound > 0 ? (linesHit / linesFound) * 100 : 100;
- data.branchCoverage = branchesFound > 0 ? (branchesHit / branchesFound) * 100 : 100;
- data.functionCoverage = functionsFound > 0 ? (functionsHit / functionsFound) * 100 : 100;
- data.statementCoverage = data.lineCoverage; // Often equivalent in LCOV
-
- files.push(data);
+ return this.buildReport(files);
}
- return files;
-}
-
-/**
- * Parse Istanbul/C8 JSON format coverage report
- */
-export function parseIstanbulJson(jsonContent: string): CoverageData[] {
- const files: CoverageData[] = [];
-
- try {
- const coverage = JSON.parse(jsonContent) as Record<string, {
- path?: string;
- s?: Record<string, number>;
- b?: Record<string, number[]>;
- f?: Record<string, number>;
- statementMap?: Record<string, { start: { line: number } }>;
- branchMap?: Record<string, { line: number; type?: string }>;
- fnMap?: Record<string, { name: string }>;
- // Summary format
- lines?: { total: number; covered: number; pct: number };
- statements?: { total: number; covered: number; pct: number };
- functions?: { total: number; covered: number; pct: number };
- branches?: { total: number; covered: number; pct: number };
- }>;
-
- for (const [filePath, fileData] of Object.entries(coverage)) {
- // Skip 'total' entry in summary format
- if (filePath === 'total') continue;
-
- const data: CoverageData = {
- filePath: fileData.path || filePath,
- lineCoverage: 0,
- branchCoverage: 0,
- functionCoverage: 0,
- statementCoverage: 0,
- uncoveredLines: [],
- uncoveredBranches: [],
- uncoveredFunctions: [],
- totalLines: 0,
- coveredLines: 0,
- };
-
- // Handle summary format
- if (fileData.lines && typeof fileData.lines.pct === 'number') {
- data.lineCoverage = fileData.lines.pct;
- data.statementCoverage = fileData.statements?.pct ?? fileData.lines.pct;
- data.branchCoverage = fileData.branches?.pct ?? 100;
- data.functionCoverage = fileData.functions?.pct ?? 100;
- data.totalLines = fileData.lines.total;
- data.coveredLines = fileData.lines.covered;
- files.push(data);
- continue;
- }
-
- // Handle detailed format
- if (fileData.s && fileData.statementMap) {
- let statementsTotal = 0;
- let statementsCovered = 0;
-
- for (const [stmtId, hitCount] of Object.entries(fileData.s)) {
- statementsTotal++;
- if (hitCount > 0) {
- statementsCovered++;
- } else {
- const stmtInfo = fileData.statementMap[stmtId];
- if (stmtInfo?.start?.line) {
- data.uncoveredLines.push(stmtInfo.start.line);
- }
- }
- }
-
- data.statementCoverage = statementsTotal > 0
- ? (statementsCovered / statementsTotal) * 100
- : 100;
- data.lineCoverage = data.statementCoverage;
- data.totalLines = statementsTotal;
- data.coveredLines = statementsCovered;
- }
-
- // Handle branch coverage
- if (fileData.b && fileData.branchMap) {
- let branchesTotal = 0;
- let branchesCovered = 0;
-
- for (const [branchId, hits] of Object.entries(fileData.b)) {
- for (const hitCount of hits) {
- branchesTotal++;
- if (hitCount > 0) {
- branchesCovered++;
- } else {
- const branchInfo = fileData.branchMap[branchId];
- if (branchInfo) {
- data.uncoveredBranches.push({
- line: branchInfo.line,
- type: (branchInfo.type || 'unknown') as UncoveredBranch['type'],
- });
- }
- }
- }
- }
-
- data.branchCoverage = branchesTotal > 0
- ? (branchesCovered / branchesTotal) * 100
- : 100;
- }
-
- // Handle function coverage
- if (fileData.f && fileData.fnMap) {
- let functionsTotal = 0;
- let functionsCovered = 0;
-
- for (const [fnId, hitCount] of Object.entries(fileData.f)) {
- functionsTotal++;
- if (hitCount > 0) {
- functionsCovered++;
- } else {
- const fnInfo = fileData.fnMap[fnId];
- if (fnInfo?.name) {
- data.uncoveredFunctions.push(fnInfo.name);
- }
- }
- }
-
- data.functionCoverage = functionsTotal > 0
- ? (functionsCovered / functionsTotal) * 100
- : 100;
- }
-
- // Deduplicate uncovered lines
- data.uncoveredLines = Array.from(new Set(data.uncoveredLines)).sort((a, b) => a - b);
-
- files.push(data);
+ private parseIstanbul(data: Record<string, unknown>): CoverageReport {
+ const files: FileCoverage[] = [];
+ for (const [path, coverage] of Object.entries(data)) {
+ const cov = coverage as Record<string, unknown>;
+ const statements = cov.s as Record<string, number>;
+ const functions = cov.f as Record<string, number>;
+ const branches = cov.b as Record<string, number[]>;
+ const statementCovered = Object.values(statements).filter(v => v > 0).length;
+ const statementTotal = Object.values(statements).length;
+ const functionCovered = Object.values(functions).filter(v => v > 0).length;
+ const functionTotal = Object.values(functions).length;
+ const branchCovered = Object.values(branches).flat().filter(v => v > 0).length;
+ const branchTotal = Object.values(branches).flat().length;
+ files.push({
+ path, lineCoverage: statementTotal > 0 ? (statementCovered / statementTotal) * 100 : 100,
+ branchCoverage: branchTotal > 0 ? (branchCovered / branchTotal) * 100 : 100,
+ functionCoverage: functionTotal > 0 ? (functionCovered / functionTotal) * 100 : 100,
+ statementCoverage: statementTotal > 0 ? (statementCovered / statementTotal) * 100 : 100,
+ uncoveredLines: [], totalLines: statementTotal, coveredLines: statementCovered,
+ });
}
- } catch {
- // Return empty array on parse error
+ return this.buildReport(files);
}
- return files;
-}
-
-/**
- * Load and parse coverage data from project
- */
-export async function loadCoverageData(projectRoot: string): Promise<{
- data: CoverageData[];
- format: 'lcov' | 'istanbul' | 'c8' | 'none';
- reportPath: string | null;
-}> {
- const reports = findCoverageReports(projectRoot);
-
- if (reports.length === 0) {
- return { data: [], format: 'none', reportPath: null };
- }
-
- // Prefer lcov format for most detailed data
- const lcovReport = reports.find(r => r.type === 'lcov');
- if (lcovReport) {
- const content = readFileSync(lcovReport.path, 'utf-8');
- return {
- data: parseLcov(content),
- format: 'lcov',
- reportPath: lcovReport.path,
- };
- }
-
- // Fall back to istanbul/c8 JSON
- const jsonReport = reports.find(r => r.type === 'istanbul' || r.type === 'c8');
- if (jsonReport) {
- const content = readFileSync(jsonReport.path, 'utf-8');
- return {
- data: parseIstanbulJson(content),
- format: jsonReport.type,
- reportPath: jsonReport.path,
- };
- }
-
- return { data: [], format: 'none', reportPath: null };
-}
-
-// ============================================================================
-// Coverage Analysis
-// ============================================================================
-
-/**
- * Calculate file complexity based on size and structure
- */
-function calculateComplexity(filePath: string, projectRoot: string): number {
- const fullPath = resolve(projectRoot, filePath);
-
- try {
- if (!existsSync(fullPath)) return 1;
-
- const content = readFileSync(fullPath, 'utf-8');
- const lines = content.split('\n');
- const lineCount = lines.length;
-
- // Basic complexity heuristics
- let complexity = 1;
-
- // Line count factor
- if (lineCount > 500) complexity += 3;
- else if (lineCount > 200) complexity += 2;
- else if (lineCount > 100) complexity += 1;
-
- // Control flow complexity (simple estimation)
- const controlFlowKeywords = content.match(
- /\b(if|else|switch|case|for|while|do|try|catch|throw)\b/g
- );
- if (controlFlowKeywords) {
- complexity += Math.min(5, Math.floor(controlFlowKeywords.length / 10));
+ private parseCobertura(data: string): CoverageReport {
+ const files: FileCoverage[] = [];
+ const classMatches = data.matchAll(/<class[^>]*filename="([^"]+)"[^>]*line-rate="([^"]+)"[^>]*branch-rate="([^"]+)"[^>]*>/g);
+ for (const match of classMatches) {
+ files.push({
+ path: match[1], lineCoverage: parseFloat(match[2]) * 100, branchCoverage: parseFloat(match[3]) * 100,
+ functionCoverage: parseFloat(match[2]) * 100, statementCoverage: parseFloat(match[2]) * 100,
+ uncoveredLines: [], totalLines: 0, coveredLines: 0,
+ });
}
-
- // Class/function count
- const declarations = content.match(
- /\b(class|function|const\s+\w+\s*=\s*(async\s+)?\(|=>\s*{)/g
- );
- if (declarations) {
- complexity += Math.min(3, Math.floor(declarations.length / 5));
- }
-
- return Math.min(10, complexity);
- } catch {
- return 1;
+ return this.buildReport(files);
}
-}
-
-/**
- * Determine gap type based on coverage percentage
- */
-function determineGapType(coverage: number): 'critical' | 'high' | 'medium' | 'low' {
- if (coverage < 20) return 'critical';
- if (coverage < 50) return 'high';
- if (coverage < 70) return 'medium';
- return 'low';
-}
-
-/**
- * Suggest agents based on file type and coverage gap
- */
-function suggestAgentsForFile(
- filePath: string,
- coverageData: CoverageData,
- gapType: 'critical' | 'high' | 'medium' | 'low'
-): string[] {
- const ext = extname(filePath).toLowerCase();
- const fileName = basename(filePath).toLowerCase();
- const agents: string[] = [];
- // Test files need tester primarily
- if (fileName.includes('.test.') || fileName.includes('.spec.')) {
- agents.push('tester', 'reviewer');
- return agents;
+ private parseJson(data: Record<string, unknown>): CoverageReport {
+ if (Array.isArray(data)) return this.buildReport(data as FileCoverage[]);
+ const files: FileCoverage[] = [];
+ for (const [path, coverage] of Object.entries(data)) {
+ const cov = coverage as Partial<FileCoverage>;
+ files.push({
+ path, lineCoverage: cov.lineCoverage || 0, branchCoverage: cov.branchCoverage || 0,
+ functionCoverage: cov.functionCoverage || 0, statementCoverage: cov.statementCoverage || 0,
+ uncoveredLines: cov.uncoveredLines || [], totalLines: cov.totalLines || 0, coveredLines: cov.coveredLines || 0,
+ });
+ }
+ return this.buildReport(files);
}
- // Based on file extension
- const extAgentMap: Record<string, string[]> = {
- '.ts': ['coder', 'tester', 'reviewer'],
- '.tsx': ['coder', 'tester', 'reviewer'],
- '.js': ['coder', 'tester'],
- '.jsx': ['coder', 'tester'],
- '.py': ['coder', 'tester', 'ml-developer'],
- '.go': ['coder', 'tester'],
- '.rs': ['coder', 'tester', 'performance-engineer'],
- };
-
- // Based on directory/file purpose
- if (filePath.includes('/api/') || filePath.includes('/routes/')) {
- agents.push('coder', 'tester', 'security-architect');
- } else if (filePath.includes('/auth/') || filePath.includes('security')) {
- agents.push('security-architect', 'tester', 'coder');
- } else if (filePath.includes('/utils/') || filePath.includes('/helpers/')) {
- agents.push('coder', 'tester');
- } else if (filePath.includes('/services/')) {
- agents.push('coder', 'tester', 'architect');
- } else {
- agents.push(...(extAgentMap[ext] || ['coder', 'tester']));
+ private finalizeFileCoverage(partial: Partial<FileCoverage>): FileCoverage {
+ const lineCoverage = partial.totalLines && partial.totalLines > 0 ? (partial.coveredLines || 0) / partial.totalLines * 100 : 100;
+ return { path: partial.path || 'unknown', lineCoverage, branchCoverage: lineCoverage, functionCoverage: lineCoverage, statementCoverage: lineCoverage, uncoveredLines: partial.uncoveredLines || [], totalLines: partial.totalLines || 0, coveredLines: partial.coveredLines || 0 };
}
- // For critical gaps, add reviewer
- if (gapType === 'critical' && !agents.includes('reviewer')) {
- agents.push('reviewer');
+ private buildReport(files: FileCoverage[]): CoverageReport {
+ const totalLines = files.reduce((sum, f) => sum + f.totalLines, 0);
+ const coveredLines = files.reduce((sum, f) => sum + f.coveredLines, 0);
+ const overall = totalLines > 0 ? (coveredLines / totalLines) * 100 : 100;
+ const avgLine = files.length > 0 ? files.reduce((sum, f) => sum + f.lineCoverage, 0) / files.length : 100;
+ const avgBranch = files.length > 0 ? files.reduce((sum, f) => sum + f.branchCoverage, 0) / files.length : 100;
+ const avgFunction = files.length > 0 ? files.reduce((sum, f) => sum + f.functionCoverage, 0) / files.length : 100;
+ const avgStatement = files.length > 0 ? files.reduce((sum, f) => sum + f.statementCoverage, 0) / files.length : 100;
+ const sortedByLine = [...files].sort((a, b) => a.lineCoverage - b.lineCoverage);
+ return { overall, byType: { line: avgLine, branch: avgBranch, function: avgFunction, statement: avgStatement }, byFile: files, lowestCoverage: sortedByLine.slice(0, 5), highestCoverage: sortedByLine.slice(-5).reverse(), uncoveredCritical: this.findCriticalUncovered(files), timestamp: Date.now() };
}
- // For uncovered branches, add architect for complex logic
- if (coverageData.uncoveredBranches.length > 5) {
- if (!agents.includes('architect')) {
- agents.push('architect');
+ private findCriticalUncovered(files: FileCoverage[]): string[] {
+ const critical: string[] = [];
+ const criticalPatterns = [/auth/, /security/, /payment/, /core/, /main/, /index/];
+ for (const file of files) {
+ if (file.lineCoverage < this.config.minCoverage) {
+ for (const pattern of criticalPatterns) { if (pattern.test(file.path)) { critical.push(file.path); break; } }
+ }
}
+ return critical.slice(0, 10);
}
- return Array.from(new Set(agents)).slice(0, 4);
-}
-
-/**
- * Calculate priority score for coverage gap
- */
-function calculatePriority(
- coverageData: CoverageData,
- complexity: number,
- gapType: 'critical' | 'high' | 'medium' | 'low'
-): number {
- // Base priority from gap type
- const gapPriority: Record<string, number> = {
- critical: 100,
- high: 75,
- medium: 50,
- low: 25,
- };
-
- let priority = gapPriority[gapType];
-
- // Add complexity factor (0-30 points)
- priority += complexity * 3;
-
- // Add uncovered lines factor (0-20 points)
- const uncoveredRatio = coverageData.uncoveredLines.length / Math.max(1, coverageData.totalLines);
- priority += Math.min(20, uncoveredRatio * 50);
-
- // Add branch coverage factor (0-15 points)
- if (coverageData.branchCoverage < 50) {
- priority += 15;
- } else if (coverageData.branchCoverage < 75) {
- priority += 8;
+ private calculateGaps(coverage: CoverageReport): CoverageRouteResult['gaps'] {
+ const gaps: CoverageRouteResult['gaps'] = [];
+ for (const file of coverage.byFile) {
+ if (file.lineCoverage < this.config.targetCoverage) {
+ const gap = this.config.targetCoverage - file.lineCoverage;
+ gaps.push({ file: file.path, currentCoverage: file.lineCoverage, targetCoverage: this.config.targetCoverage, gap, suggestedTests: this.suggestTests(file) });
+ }
+ }
+ return gaps.sort((a, b) => b.gap - a.gap).slice(0, 10);
}
- // Important file patterns get boost
- const fileName = basename(coverageData.filePath);
- if (fileName.includes('service') || fileName.includes('controller')) {
- priority += 10;
+ private suggestTests(file: FileCoverage): string[] {
+ const suggestions: string[] = [];
+ if (file.uncoveredLines.length > 10) suggestions.push('Add unit tests for uncovered code paths');
+ if (file.branchCoverage < 50) suggestions.push('Add branch coverage tests (if/else paths)');
+ if (file.functionCoverage < 80) suggestions.push('Add tests for untested functions');
+ if (/api|endpoint|route|handler/.test(file.path)) suggestions.push('Add integration tests for API endpoints');
+ return suggestions.slice(0, 3);
}
- if (fileName.includes('auth') || fileName.includes('security')) {
- priority += 15;
- }
-
- return Math.min(200, priority);
-}
-/**
- * Analyze coverage and identify gaps
- */
-export function analyzeCoverageGaps(
- coverageData: CoverageData[],
- projectRoot: string,
- threshold: number = 80
-): CoverageGap[] {
- const gaps: CoverageGap[] = [];
-
- for (const data of coverageData) {
- const avgCoverage = (
- data.lineCoverage +
- data.branchCoverage +
- data.functionCoverage +
- data.statementCoverage
- ) / 4;
-
- if (avgCoverage >= threshold) continue;
-
- const gapType = determineGapType(avgCoverage);
- const complexity = calculateComplexity(data.filePath, projectRoot);
- const suggestedAgents = suggestAgentsForFile(data.filePath, data, gapType);
- const priority = calculatePriority(data, complexity, gapType);
-
- // Generate reason
- const reasons: string[] = [];
- if (data.lineCoverage < threshold) {
- reasons.push(`line coverage ${data.lineCoverage.toFixed(1)}%`);
+ private prioritizeFiles(coverage: CoverageReport, changedFiles?: string[]): string[] {
+ let targetFiles = coverage.lowestCoverage.map(f => f.path);
+ if (changedFiles && changedFiles.length > 0) {
+ const changedWithLowCoverage = coverage.byFile.filter(f => changedFiles.some(cf => f.path.includes(cf))).filter(f => f.lineCoverage < this.config.targetCoverage).map(f => f.path);
+ targetFiles = [...new Set([...changedWithLowCoverage, ...targetFiles])];
}
- if (data.branchCoverage < threshold) {
- reasons.push(`branch coverage ${data.branchCoverage.toFixed(1)}%`);
- }
- if (data.uncoveredFunctions.length > 0) {
- reasons.push(`${data.uncoveredFunctions.length} uncovered functions`);
- }
-
- gaps.push({
- filePath: data.filePath,
- coveragePercent: avgCoverage,
- gapType,
- complexity,
- priority,
- suggestedAgents,
- uncoveredLines: data.uncoveredLines.slice(0, 20), // Limit for output
- reason: reasons.join(', ') || 'Below threshold',
- });
+ return targetFiles.slice(0, 10);
}
- // Sort by priority (descending)
- return gaps.sort((a, b) => b.priority - a.priority);
-}
-
-/**
- * Generate coverage summary
- */
-export function generateCoverageSummary(
- coverageData: CoverageData[],
- threshold: number = 80
-): CoverageSummary {
- if (coverageData.length === 0) {
- return {
- totalFiles: 0,
- overallLineCoverage: 0,
- overallBranchCoverage: 0,
- overallFunctionCoverage: 0,
- overallStatementCoverage: 0,
- filesBelowThreshold: 0,
- coverageThreshold: threshold,
- };
+ private determineAction(coverage: CoverageReport, gaps: CoverageRouteResult['gaps']): CoverageRouteResult['action'] {
+ if (coverage.overall < this.config.minCoverage) return 'prioritize';
+ if (gaps.length > 5) return 'add-tests';
+ if (coverage.overall < this.config.targetCoverage) return 'review-coverage';
+ return 'skip';
}
- const totals = coverageData.reduce(
- (acc, data) => {
- acc.line += data.lineCoverage;
- acc.branch += data.branchCoverage;
- acc.function += data.functionCoverage;
- acc.statement += data.statementCoverage;
- return acc;
- },
- { line: 0, branch: 0, function: 0, statement: 0 }
- );
-
- const fileCount = coverageData.length;
- const avgLine = totals.line / fileCount;
- const avgBranch = totals.branch / fileCount;
- const avgFunction = totals.function / fileCount;
- const avgStatement = totals.statement / fileCount;
-
- const belowThreshold = coverageData.filter(d => {
- const avg = (d.lineCoverage + d.branchCoverage + d.functionCoverage + d.statementCoverage) / 4;
- return avg < threshold;
- }).length;
-
- return {
- totalFiles: fileCount,
- overallLineCoverage: avgLine,
- overallBranchCoverage: avgBranch,
- overallFunctionCoverage: avgFunction,
- overallStatementCoverage: avgStatement,
- filesBelowThreshold: belowThreshold,
- coverageThreshold: threshold,
- };
-}
-
-// ============================================================================
-// Main API Functions
-// ============================================================================
-
-/**
- * Route a task with coverage awareness
- *
- * CLI Usage:
- * claude-flow route "fix bug" --coverage-aware
- */
-export async function coverageRoute(
- task: string,
- options: {
- projectRoot?: string;
- threshold?: number;
- useRuvector?: boolean;
- } = {}
-): Promise<CoverageRouteResult> {
- const projectRoot = options.projectRoot || process.cwd();
- const threshold = options.threshold ?? 80;
- const useRuvector = options.useRuvector !== false;
-
- // Load coverage data
- const { data: coverageData, format, reportPath } = await loadCoverageData(projectRoot);
-
- // Analyze gaps
- const gaps = coverageData.length > 0
- ? analyzeCoverageGaps(coverageData, projectRoot, threshold)
- : [];
-
- // Try ruvector integration if available
- if (useRuvector && coverageData.length > 0) {
- const ruvectorResult = await callRuvectorRoute(task, coverageData);
- if (ruvectorResult && typeof ruvectorResult === 'object') {
- // Merge ruvector insights if available
- // (ruvector provides more sophisticated ML-based routing)
+ private calculatePriority(coverage: CoverageReport, changedFiles?: string[]): number {
+ let priority = 5;
+ if (coverage.overall < 50) priority += 4; else if (coverage.overall < 70) priority += 2; else if (coverage.overall < 85) priority += 1;
+ priority += Math.min(3, coverage.uncoveredCritical.length);
+ if (changedFiles && changedFiles.length > 0) {
+ const changedLowCoverage = coverage.byFile.filter(f => changedFiles.some(cf => f.path.includes(cf))).filter(f => f.lineCoverage < this.config.minCoverage);
+ priority += Math.min(2, changedLowCoverage.length);
}
+ return Math.min(10, priority);
}
- // Determine primary agent based on task + coverage
- const taskLower = task.toLowerCase();
- let primaryAgent = 'coder';
- let confidence = 0.75;
- let reason = 'Default routing based on task analysis';
- let coverageImpact = 'No coverage data available';
-
- if (gaps.length > 0) {
- // Find most relevant gap for task
- const criticalGaps = gaps.filter(g => g.gapType === 'critical' || g.gapType === 'high');
-
- if (criticalGaps.length > 0) {
- primaryAgent = criticalGaps[0].suggestedAgents[0] || 'tester';
- confidence = 0.85;
- reason = `Critical coverage gap in ${criticalGaps[0].filePath}`;
- coverageImpact = `${criticalGaps.length} high-priority files need attention`;
- }
-
- // Override based on task keywords
- if (taskLower.includes('test') || taskLower.includes('coverage')) {
- primaryAgent = 'tester';
- confidence = 0.9;
- reason = 'Task explicitly mentions testing/coverage';
- } else if (taskLower.includes('security') || taskLower.includes('auth')) {
- primaryAgent = 'security-architect';
- confidence = 0.88;
- reason = 'Security-related task detected';
+ private recommendTestTypes(gaps: CoverageRouteResult['gaps']): CoverageRouteResult['testTypes'] {
+ const types: Set<'unit' | 'integration' | 'e2e'> = new Set(['unit']);
+ for (const gap of gaps) {
+ if (/api|endpoint|route|handler|service/.test(gap.file)) types.add('integration');
+ if (/page|component|view|ui/.test(gap.file)) types.add('e2e');
}
+ return Array.from(types);
}
- // Generate suggestions
- const suggestions: string[] = [];
- if (format === 'none') {
- suggestions.push('Run tests with coverage to enable coverage-aware routing');
- suggestions.push('Supported formats: lcov, istanbul (c8), nyc');
- } else {
- if (gaps.length === 0) {
- suggestions.push('All files meet coverage threshold');
- } else {
- suggestions.push(`Focus on ${gaps.slice(0, 3).map(g => basename(g.filePath)).join(', ')}`);
- if (gaps.some(g => g.gapType === 'critical')) {
- suggestions.push('Critical coverage gaps detected - prioritize testing');
- }
- }
+ private estimateEffort(gaps: CoverageRouteResult['gaps']): number {
+ let effort = 0;
+ for (const gap of gaps) effort += (gap.gap / 10) * 0.5;
+ return Math.round(effort * 10) / 10;
}
- const summary = generateCoverageSummary(coverageData, threshold);
-
- return {
- success: true,
- task,
- coverageAware: format !== 'none',
- gaps: gaps.slice(0, 10), // Limit output
- routing: {
- primaryAgent,
- confidence,
- reason,
- coverageImpact,
- },
- suggestions,
- metrics: {
- filesAnalyzed: coverageData.length,
- totalGaps: gaps.length,
- criticalGaps: gaps.filter(g => g.gapType === 'critical').length,
- avgCoverage: summary.overallLineCoverage,
- },
- };
-}
-
-/**
- * Suggest coverage improvements for a path
- *
- * CLI Usage:
- * claude-flow route --coverage-suggest src/
- */
-export async function coverageSuggest(
- path: string,
- options: {
- projectRoot?: string;
- threshold?: number;
- useRuvector?: boolean;
- limit?: number;
- } = {}
-): Promise<CoverageSuggestResult> {
- const projectRoot = options.projectRoot || process.cwd();
- const threshold = options.threshold ?? 80;
- const useRuvector = options.useRuvector !== false;
- const limit = options.limit ?? 20;
-
- // Load coverage data
- const { data: coverageData, format } = await loadCoverageData(projectRoot);
-
- // Filter to requested path
- const normalizedPath = path.startsWith('/') ? path : join(projectRoot, path);
- const relativePath = relative(projectRoot, normalizedPath);
-
- const filteredData = coverageData.filter(d => {
- const filePath = d.filePath.replace(/^\.?\//, '');
- return filePath.startsWith(relativePath) || filePath.includes(path);
- });
-
- // Analyze gaps
- const gaps = analyzeCoverageGaps(filteredData, projectRoot, threshold);
-
- // Try ruvector integration
- const ruvectorAvail = useRuvector ? await checkRuvectorAvailable() : false;
- if (ruvectorAvail && filteredData.length > 0) {
- await callRuvectorSuggest(path, filteredData);
+ private calculateImpact(coverage: CoverageReport, targetFiles: string[]): number {
+ const potentialGain = targetFiles.reduce((sum, file) => {
+ const fileCov = coverage.byFile.find(f => f.path === file);
+ return fileCov ? sum + (this.config.targetCoverage - fileCov.lineCoverage) : sum;
+ }, 0);
+ return Math.min(100, Math.round(potentialGain / targetFiles.length || 0));
}
-
- const summary = generateCoverageSummary(filteredData, threshold);
-
- return {
- success: true,
- path,
- suggestions: gaps.slice(0, limit),
- summary,
- prioritizedFiles: gaps.slice(0, 10).map(g => g.filePath),
- ruvectorAvailable: ruvectorAvail,
- };
}
-/**
- * Get all coverage gaps in project
- *
- * CLI Usage:
- * claude-flow route --coverage-gaps
- */
-export async function coverageGaps(
- options: {
- projectRoot?: string;
- threshold?: number;
- useRuvector?: boolean;
- groupByAgent?: boolean;
- } = {}
-): Promise<CoverageGapsResult> {
- const projectRoot = options.projectRoot || process.cwd();
- const threshold = options.threshold ?? 80;
- const useRuvector = options.useRuvector !== false;
- const groupByAgent = options.groupByAgent ?? true;
-
- // Load coverage data
- const { data: coverageData } = await loadCoverageData(projectRoot);
-
- // Analyze all gaps
- const gaps = analyzeCoverageGaps(coverageData, projectRoot, threshold);
-
- // Group by suggested agent
- const agentAssignments: Record<string, string[]> = {};
- if (groupByAgent) {
- for (const gap of gaps) {
- const primaryAgent = gap.suggestedAgents[0] || 'tester';
- if (!agentAssignments[primaryAgent]) {
- agentAssignments[primaryAgent] = [];
- }
- agentAssignments[primaryAgent].push(gap.filePath);
- }
- }
-
- const summary = generateCoverageSummary(coverageData, threshold);
- const ruvectorAvail = useRuvector ? await checkRuvectorAvailable() : false;
-
- return {
- success: true,
- gaps,
- summary,
- agentAssignments,
- ruvectorAvailable: ruvectorAvail,
- };
+export function createCoverageRouter(config?: Partial<CoverageRouterConfig>): CoverageRouter {
+ return new CoverageRouter(config);
}
-
-// ============================================================================
-// Export
-// ============================================================================
-
-export default {
- coverageRoute,
- coverageSuggest,
- coverageGaps,
- loadCoverageData,
- analyzeCoverageGaps,
- generateCoverageSummary,
- parseLcov,
- parseIstanbulJson,
- findCoverageReports,
-};
diff --git a/v3/@claude-flow/cli/src/ruvector/diff-classifier.ts b/v3/@claude-flow/cli/src/ruvector/diff-classifier.ts
index 171ffc3bd7..41254ad757 100644
--- a/v3/@claude-flow/cli/src/ruvector/diff-classifier.ts
+++ b/v3/@claude-flow/cli/src/ruvector/diff-classifier.ts
@@ -1,714 +1,296 @@
/**
- * Diff Classification Module
- * Analyzes git diffs for change risk assessment and classification
- *
- * Uses ruvector's hooks_diff_analyze and hooks_diff_classify when available,
- * with graceful fallback to built-in analysis.
+ * Diff Classifier for Change Analysis
*/
-import { execSync, spawnSync } from 'child_process';
-
-// ============================================
-// Types
-// ============================================
-
-export type RiskLevel = 'low-risk' | 'medium-risk' | 'high-risk' | 'critical';
+export interface DiffClassifierConfig {
+ maxDiffSize: number;
+ classifyByImpact: boolean;
+ detectRefactoring: boolean;
+ minConfidence: number;
+}
-export interface DiffFile {
- path: string;
- status: 'added' | 'modified' | 'deleted' | 'renamed';
- additions: number;
- deletions: number;
- hunks: number;
- binary: boolean;
- oldPath?: string; // For renamed files
+export interface DiffHunk {
+ oldStart: number;
+ oldLines: number;
+ newStart: number;
+ newLines: number;
+ content: string;
+ changes: DiffChange[];
}
-export interface DiffRiskAssessment {
- overall: RiskLevel;
- score: number; // 0-100
- breakdown: {
- fileCount: number;
- totalChanges: number;
- highRiskFiles: string[];
- securityConcerns: string[];
- breakingChanges: string[];
- testCoverage: 'adequate' | 'insufficient' | 'unknown';
- };
+export interface DiffChange {
+ type: 'add' | 'remove' | 'context';
+ lineNumber: number;
+ content: string;
}
export interface DiffClassification {
- category: string;
- subcategory?: string;
+ primary: 'feature' | 'bugfix' | 'refactor' | 'docs' | 'test' | 'config' | 'style' | 'unknown';
+ secondary: string[];
confidence: number;
- reasoning: string;
+ impactLevel: 'low' | 'medium' | 'high' | 'critical';
+ suggestedReviewers: string[];
+ testingStrategy: string[];
+ riskFactors: string[];
}
-export interface FileRisk {
+export interface FileDiff {
path: string;
- risk: RiskLevel;
- score: number;
- reasons: string[];
-}
-
-export interface DiffAnalysisResult {
- ref: string;
- timestamp: string;
- files: DiffFile[];
- risk: DiffRiskAssessment;
+ hunks: DiffHunk[];
+ additions: number;
+ deletions: number;
classification: DiffClassification;
- fileRisks: FileRisk[];
- recommendedReviewers: string[];
- summary: string;
-}
-
-// ============================================
-// Risk Patterns
-// ============================================
-
-const HIGH_RISK_PATTERNS = [
- { pattern: /auth|authentication|login|password|secret|token|key|credential/i, reason: 'Security-sensitive code' },
- { pattern: /payment|billing|checkout|stripe|paypal|transaction/i, reason: 'Payment processing code' },
- { pattern: /database|migration|schema|sql|query/i, reason: 'Database changes' },
- { pattern: /security|permission|access|rbac|acl/i, reason: 'Security/permission changes' },
- { pattern: /config|\.env|environment/i, reason: 'Configuration changes' },
- { pattern: /api\/v\d|breaking|deprecat/i, reason: 'Potential API breaking changes' },
- { pattern: /crypto|encrypt|decrypt|hash/i, reason: 'Cryptography code' },
-];
-
-const MEDIUM_RISK_PATTERNS = [
- { pattern: /core|base|foundation|lib\//i, reason: 'Core library changes' },
- { pattern: /interface|type|contract/i, reason: 'Interface/contract changes' },
- { pattern: /package\.json|yarn\.lock|package-lock/i, reason: 'Dependency changes' },
- { pattern: /ci|cd|workflow|pipeline|\.github/i, reason: 'CI/CD changes' },
- { pattern: /docker|kubernetes|k8s|helm/i, reason: 'Infrastructure changes' },
-];
-
-const SAFE_PATTERNS = [
- { pattern: /\.md$|readme|docs\//i, reason: 'Documentation' },
- { pattern: /\.test\.|\.spec\.|__tests__/i, reason: 'Test files' },
- { pattern: /\.snap$|snapshot/i, reason: 'Snapshot files' },
- { pattern: /\.css$|\.scss$|\.less$|\.styl/i, reason: 'Style files' },
- { pattern: /comments?|todo|fixme/i, reason: 'Comment changes' },
-];
-
-// File extension to reviewer mapping
-const REVIEWER_PATTERNS: Record<string, string[]> = {
- '.ts': ['typescript-expert', 'coder'],
- '.tsx': ['frontend-expert', 'coder', 'reviewer'],
- '.py': ['python-expert', 'coder'],
- '.go': ['go-expert', 'coder'],
- '.rs': ['rust-expert', 'coder'],
- '.sql': ['database-expert', 'architect'],
- '.sh': ['devops-expert', 'security-expert'],
- '.dockerfile': ['devops-expert', 'security-expert'],
- '.yaml': ['devops-expert', 'architect'],
- '.yml': ['devops-expert', 'architect'],
- '.json': ['coder', 'architect'],
- 'security': ['security-expert', 'architect'],
- 'auth': ['security-expert', 'architect'],
- 'payment': ['security-expert', 'senior-reviewer'],
-};
-
-// ============================================
-// RuVector Integration (Graceful Fallback)
-// ============================================
-
-interface RuVectorResult {
- available: boolean;
- analysis?: unknown;
- classification?: unknown;
}
-/**
- * Attempts to use ruvector's diff analysis when available
- */
-async function tryRuVectorAnalysis(diffContent: string): Promise<RuVectorResult> {
- try {
- // Check if ruvector is available
- const result = spawnSync('npx', ['ruvector', '--version'], {
- encoding: 'utf-8',
- timeout: 5000,
- });
-
- if (result.status !== 0) {
- return { available: false };
- }
-
- // Try hooks_diff_analyze
- const analyzeResult = spawnSync('npx', ['ruvector', 'hooks_diff_analyze'], {
- input: diffContent,
- encoding: 'utf-8',
- timeout: 30000,
- });
-
- if (analyzeResult.status === 0 && analyzeResult.stdout) {
- try {
- const analysis = JSON.parse(analyzeResult.stdout);
- return { available: true, analysis };
- } catch {
- // JSON parse failed, continue with fallback
- }
- }
-
- return { available: false };
- } catch {
- return { available: false };
- }
+export interface DiffAnalysis {
+ files: FileDiff[];
+ overall: DiffClassification;
+ stats: {
+ totalAdditions: number;
+ totalDeletions: number;
+ filesChanged: number;
+ avgConfidence: number;
+ };
+ timestamp: number;
}
-/**
- * Attempts to use ruvector's diff classification when available
- */
-async function tryRuVectorClassify(diffContent: string): Promise<RuVectorResult> {
- try {
- const result = spawnSync('npx', ['ruvector', 'hooks_diff_classify'], {
- input: diffContent,
- encoding: 'utf-8',
- timeout: 30000,
- });
+const DEFAULT_CONFIG: DiffClassifierConfig = {
+ maxDiffSize: 10000,
+ classifyByImpact: true,
+ detectRefactoring: true,
+ minConfidence: 0.5,
+};
- if (result.status === 0 && result.stdout) {
- try {
- const classification = JSON.parse(result.stdout);
- return { available: true, classification };
- } catch {
- // JSON parse failed, continue with fallback
- }
- }
+const CLASSIFICATION_PATTERNS: Record<string, RegExp[]> = {
+ feature: [/^feat/, /add.*feature/, /implement/, /new.*functionality/i],
+ bugfix: [/^fix/, /bug/, /patch/, /resolve.*issue/i, /hotfix/i],
+ refactor: [/^refactor/, /restructure/, /reorganize/, /cleanup/i, /rename/i],
+ docs: [/^docs?/, /documentation/, /readme/i, /comment/i, /\.md$/i],
+ test: [/^test/, /spec/, /\.test\.[jt]sx?$/, /\.spec\.[jt]sx?$/, /__tests__/],
+ config: [/^config/, /\.config\./, /package\.json/, /tsconfig/, /\.env/],
+ style: [/^style/, /format/, /lint/, /prettier/, /eslint/],
+};
- return { available: false };
- } catch {
- return { available: false };
- }
-}
+const IMPACT_KEYWORDS: Record<string, number> = {
+ security: 3, auth: 3, payment: 3, database: 2, api: 2, core: 2,
+ util: 1, helper: 1, test: 0, mock: 0, fixture: 0,
+};
-// ============================================
-// Git Diff Parsing
-// ============================================
+export class DiffClassifier {
+ private config: DiffClassifierConfig;
+ private ruvectorEngine: unknown = null;
+ private useNative = false;
+ private classificationCache: Map<string, DiffClassification> = new Map();
-/**
- * Get git diff for a given ref
- */
-export function getGitDiff(ref: string = 'HEAD~1', cwd?: string): string {
- try {
- const result = execSync(`git diff ${ref}`, {
- cwd: cwd || process.cwd(),
- encoding: 'utf-8',
- maxBuffer: 10 * 1024 * 1024, // 10MB
- });
- return result;
- } catch (error) {
- throw new Error(`Failed to get git diff: ${error instanceof Error ? error.message : String(error)}`);
+ constructor(config: Partial<DiffClassifierConfig> = {}) {
+ this.config = { ...DEFAULT_CONFIG, ...config };
}
-}
-/**
- * Get git diff --stat for file summary
- */
-export function getGitDiffStat(ref: string = 'HEAD~1', cwd?: string): string {
- try {
- const result = execSync(`git diff --stat ${ref}`, {
- cwd: cwd || process.cwd(),
- encoding: 'utf-8',
- });
- return result;
- } catch (error) {
- throw new Error(`Failed to get git diff stat: ${error instanceof Error ? error.message : String(error)}`);
+ async initialize(): Promise<void> {
+ try {
+ const ruvector = await import('@ruvector/diff');
+ this.ruvectorEngine = (ruvector as any).createDiffClassifier?.(this.config);
+ this.useNative = !!this.ruvectorEngine;
+ } catch { this.useNative = false; }
}
-}
-
-/**
- * Get git diff --numstat for precise line counts
- */
-export function getGitDiffNumstat(ref: string = 'HEAD~1', cwd?: string): DiffFile[] {
- try {
- const numstat = execSync(`git diff --numstat ${ref}`, {
- cwd: cwd || process.cwd(),
- encoding: 'utf-8',
- });
- const nameStatus = execSync(`git diff --name-status ${ref}`, {
- cwd: cwd || process.cwd(),
- encoding: 'utf-8',
- });
-
- const files: DiffFile[] = [];
- const numstatLines = numstat.trim().split('\n').filter(Boolean);
- const statusMap = new Map<string, string>();
-
- // Parse name-status output
- nameStatus.trim().split('\n').filter(Boolean).forEach(line => {
- const parts = line.split('\t');
- if (parts.length >= 2) {
- const status = parts[0];
- const path = parts.length === 3 ? parts[2] : parts[1]; // Handle renames
- statusMap.set(path, status);
- }
- });
-
- for (const line of numstatLines) {
- const parts = line.split('\t');
- if (parts.length >= 3) {
- const additions = parts[0] === '-' ? 0 : parseInt(parts[0], 10);
- const deletions = parts[1] === '-' ? 0 : parseInt(parts[1], 10);
- const path = parts[2];
- const binary = parts[0] === '-' && parts[1] === '-';
-
- const statusCode = statusMap.get(path) || 'M';
- let status: DiffFile['status'] = 'modified';
- let oldPath: string | undefined;
-
- if (statusCode.startsWith('A')) status = 'added';
- else if (statusCode.startsWith('D')) status = 'deleted';
- else if (statusCode.startsWith('R')) {
- status = 'renamed';
- // For renames, the old path is in the numstat
- }
-
- files.push({
- path,
- status,
- additions,
- deletions,
- hunks: 1, // Approximate
- binary,
- oldPath,
- });
- }
+ parseDiff(diffContent: string): FileDiff[] {
+ const files: FileDiff[] = [];
+ const fileBlocks = diffContent.split(/^diff --git/m).filter(Boolean);
+ for (const block of fileBlocks) {
+ const pathMatch = block.match(/a\/(.+?)\s+b\/(.+)/);
+ if (!pathMatch) continue;
+ const path = pathMatch[2];
+ const hunks = this.parseHunks(block);
+ const additions = hunks.reduce((sum, h) => sum + h.changes.filter(c => c.type === 'add').length, 0);
+ const deletions = hunks.reduce((sum, h) => sum + h.changes.filter(c => c.type === 'remove').length, 0);
+ const classification = this.classifyFile(path, hunks);
+ files.push({ path, hunks, additions, deletions, classification });
}
-
return files;
- } catch (error) {
- throw new Error(`Failed to get git diff numstat: ${error instanceof Error ? error.message : String(error)}`);
}
-}
-/**
- * Get file contributors for reviewer suggestions
- */
-export function getFileContributors(filePath: string, cwd?: string): string[] {
- try {
- const result = execSync(
- `git log --format='%an' --follow -- "${filePath}" | sort | uniq -c | sort -rn | head -5`,
- {
- cwd: cwd || process.cwd(),
- encoding: 'utf-8',
- shell: '/bin/bash',
- }
- );
-
- return result
- .trim()
- .split('\n')
- .filter(Boolean)
- .map(line => line.trim().replace(/^\d+\s+/, ''))
- .filter(Boolean);
- } catch {
- return [];
+ classify(files: FileDiff[]): DiffAnalysis {
+ const overall = this.computeOverallClassification(files);
+ const stats = {
+ totalAdditions: files.reduce((sum, f) => sum + f.additions, 0),
+ totalDeletions: files.reduce((sum, f) => sum + f.deletions, 0),
+ filesChanged: files.length,
+ avgConfidence: files.length > 0 ? files.reduce((sum, f) => sum + f.classification.confidence, 0) / files.length : 0,
+ };
+ return { files, overall, stats, timestamp: Date.now() };
}
-}
-// ============================================
-// Risk Assessment
-// ============================================
-
-/**
- * Calculate risk score for a single file
- */
-export function assessFileRisk(file: DiffFile): FileRisk {
- const reasons: string[] = [];
- let score = 0;
-
- // Base score from change size
- const totalChanges = file.additions + file.deletions;
- if (totalChanges > 500) {
- score += 30;
- reasons.push(`Large change (${totalChanges} lines)`);
- } else if (totalChanges > 200) {
- score += 20;
- reasons.push(`Significant change (${totalChanges} lines)`);
- } else if (totalChanges > 50) {
- score += 10;
- }
-
- // Check high-risk patterns
- for (const { pattern, reason } of HIGH_RISK_PATTERNS) {
- if (pattern.test(file.path)) {
- score += 25;
- reasons.push(reason);
- }
- }
-
- // Check medium-risk patterns
- for (const { pattern, reason } of MEDIUM_RISK_PATTERNS) {
- if (pattern.test(file.path)) {
- score += 15;
- reasons.push(reason);
- }
- }
-
- // Reduce score for safe patterns
- for (const { pattern, reason } of SAFE_PATTERNS) {
- if (pattern.test(file.path)) {
- score = Math.max(0, score - 20);
- reasons.push(`${reason} (lower risk)`);
+ classifyCommitMessage(message: string): DiffClassification['primary'] {
+ const lowerMessage = message.toLowerCase();
+ for (const [type, patterns] of Object.entries(CLASSIFICATION_PATTERNS)) {
+ for (const pattern of patterns) {
+ if (pattern.test(lowerMessage)) return type as DiffClassification['primary'];
+ }
}
+ return 'unknown';
}
- // Deleted files are higher risk
- if (file.status === 'deleted') {
- score += 15;
- reasons.push('File deletion');
- }
-
- // Binary files need careful review
- if (file.binary) {
- score += 10;
- reasons.push('Binary file');
+ getStats(): Record<string, number | boolean> {
+ return { useNative: this.useNative, cacheSize: this.classificationCache.size };
}
- // Cap score at 100
- score = Math.min(100, score);
-
- // Determine risk level
- let risk: RiskLevel = 'low-risk';
- if (score >= 70) risk = 'critical';
- else if (score >= 50) risk = 'high-risk';
- else if (score >= 25) risk = 'medium-risk';
-
- return { path: file.path, risk, score, reasons };
-}
-
-/**
- * Calculate overall risk assessment for all files
- */
-export function assessOverallRisk(files: DiffFile[], fileRisks: FileRisk[]): DiffRiskAssessment {
- const totalChanges = files.reduce((sum, f) => sum + f.additions + f.deletions, 0);
- const highRiskFiles = fileRisks.filter(f => f.risk === 'high-risk' || f.risk === 'critical').map(f => f.path);
-
- // Security concerns
- const securityConcerns: string[] = [];
- for (const file of files) {
- if (/auth|password|secret|token|key|credential|crypto/i.test(file.path)) {
- securityConcerns.push(`Security-sensitive file: ${file.path}`);
+ clearCache(): void { this.classificationCache.clear(); }
+
+ private parseHunks(block: string): DiffHunk[] {
+ const hunks: DiffHunk[] = [];
+ const hunkMatches = block.matchAll(/@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@([^\n]*)\n([\s\S]*?)(?=@@|$)/g);
+ for (const match of hunkMatches) {
+ const oldStart = parseInt(match[1], 10);
+ const oldLines = parseInt(match[2] || '1', 10);
+ const newStart = parseInt(match[3], 10);
+ const newLines = parseInt(match[4] || '1', 10);
+ const content = match[6] || '';
+ const changes = this.parseChanges(content, newStart);
+ hunks.push({ oldStart, oldLines, newStart, newLines, content, changes });
}
+ return hunks;
}
- // Breaking changes detection
- const breakingChanges: string[] = [];
- for (const file of files) {
- if (/api\/v\d|breaking|deprecat|interface|type/i.test(file.path)) {
- if (file.deletions > file.additions) {
- breakingChanges.push(`Potential breaking change: ${file.path}`);
- }
+ private parseChanges(content: string, startLine: number): DiffChange[] {
+ const changes: DiffChange[] = [];
+ const lines = content.split('\n');
+ let lineNumber = startLine;
+ for (const line of lines) {
+ if (line.startsWith('+')) { changes.push({ type: 'add', lineNumber, content: line.substring(1) }); lineNumber++; }
+ else if (line.startsWith('-')) { changes.push({ type: 'remove', lineNumber: -1, content: line.substring(1) }); }
+ else if (line.startsWith(' ') || line === '') { changes.push({ type: 'context', lineNumber, content: line.substring(1) || '' }); lineNumber++; }
}
+ return changes;
}
- // Test coverage assessment
- const testFiles = files.filter(f => /\.test\.|\.spec\.|__tests__/i.test(f.path));
- const sourceFiles = files.filter(f => /\.(ts|tsx|js|jsx|py|go|rs)$/.test(f.path) && !/\.test\.|\.spec\./i.test(f.path));
- let testCoverage: 'adequate' | 'insufficient' | 'unknown' = 'unknown';
- if (sourceFiles.length > 0) {
- testCoverage = testFiles.length >= sourceFiles.length * 0.5 ? 'adequate' : 'insufficient';
+ private classifyFile(path: string, hunks: DiffHunk[]): DiffClassification {
+ const cacheKey = this.getCacheKey(path, hunks);
+ const cached = this.classificationCache.get(cacheKey);
+ if (cached) return cached;
+ const primary = this.determinePrimaryClassification(path, hunks);
+ const secondary = this.determineSecondaryClassifications(path, hunks, primary);
+ const confidence = this.calculateConfidence(path, hunks, primary);
+ const impactLevel = this.determineImpactLevel(path, hunks);
+ const suggestedReviewers = this.suggestReviewers(path, primary, impactLevel);
+ const testingStrategy = this.determineTestingStrategy(path, primary, impactLevel);
+ const riskFactors = this.identifyRiskFactors(path, hunks, impactLevel);
+ const classification: DiffClassification = { primary, secondary, confidence, impactLevel, suggestedReviewers, testingStrategy, riskFactors };
+ this.classificationCache.set(cacheKey, classification);
+ return classification;
}
- // Calculate overall score (weighted average)
- const avgScore = fileRisks.length > 0
- ? fileRisks.reduce((sum, f) => sum + f.score, 0) / fileRisks.length
- : 0;
-
- // Adjust for file count
- let score = avgScore;
- if (files.length > 20) score += 15;
- else if (files.length > 10) score += 10;
- else if (files.length > 5) score += 5;
-
- // Adjust for security concerns
- score += securityConcerns.length * 10;
- score += breakingChanges.length * 10;
-
- // Cap at 100
- score = Math.min(100, Math.round(score));
-
- // Determine overall risk level
- let overall: RiskLevel = 'low-risk';
- if (score >= 70) overall = 'critical';
- else if (score >= 50) overall = 'high-risk';
- else if (score >= 25) overall = 'medium-risk';
-
- return {
- overall,
- score,
- breakdown: {
- fileCount: files.length,
- totalChanges,
- highRiskFiles,
- securityConcerns,
- breakingChanges,
- testCoverage,
- },
- };
-}
-
-// ============================================
-// Classification
-// ============================================
-
-/**
- * Classify the type of change
- */
-export function classifyDiff(files: DiffFile[]): DiffClassification {
- // Count by category
- const categories = {
- feature: 0,
- bugfix: 0,
- refactor: 0,
- test: 0,
- docs: 0,
- config: 0,
- style: 0,
- infra: 0,
- security: 0,
- };
-
- for (const file of files) {
- const path = file.path.toLowerCase();
-
- if (/\.test\.|\.spec\.|__tests__/.test(path)) categories.test++;
- else if (/\.md$|readme|docs\//.test(path)) categories.docs++;
- else if (/\.css$|\.scss$|\.less$|\.styl/.test(path)) categories.style++;
- else if (/config|\.env|\.yaml|\.yml|\.json$/.test(path)) categories.config++;
- else if (/docker|kubernetes|k8s|helm|ci|cd|workflow/.test(path)) categories.infra++;
- else if (/auth|security|permission|crypto/.test(path)) categories.security++;
- else if (file.deletions > file.additions * 2) categories.refactor++;
- else if (file.status === 'added') categories.feature++;
- else categories.bugfix++;
+ private getCacheKey(path: string, hunks: DiffHunk[]): string {
+ const hunkSummary = hunks.map(h => h.oldStart + ':' + h.newStart).join(',');
+ return path + ':' + hunkSummary;
}
- // Find dominant category
- let maxCount = 0;
- let category = 'feature';
- for (const [cat, count] of Object.entries(categories)) {
- if (count > maxCount) {
- maxCount = count;
- category = cat;
+ private determinePrimaryClassification(path: string, hunks: DiffHunk[]): DiffClassification['primary'] {
+ for (const [type, patterns] of Object.entries(CLASSIFICATION_PATTERNS)) {
+ for (const pattern of patterns) { if (pattern.test(path)) return type as DiffClassification['primary']; }
}
+ const allContent = hunks.flatMap(h => h.changes.map(c => c.content)).join('\n').toLowerCase();
+ if (/function|class|interface|type\s+\w+/.test(allContent) && hunks.some(h => h.changes.filter(c => c.type === 'add').length > 10)) return 'feature';
+ if (/fix|bug|issue|error|exception/.test(allContent)) return 'bugfix';
+ if (this.config.detectRefactoring && this.isRefactoring(hunks)) return 'refactor';
+ return 'unknown';
}
- // Calculate confidence
- const total = Object.values(categories).reduce((a, b) => a + b, 0);
- const confidence = total > 0 ? Math.min(0.95, (maxCount / total) + 0.2) : 0.5;
-
- // Generate reasoning
- const reasoning = generateClassificationReasoning(category, files, categories);
-
- return {
- category,
- subcategory: getSubcategory(category, files),
- confidence,
- reasoning,
- };
-}
-
-function getSubcategory(category: string, files: DiffFile[]): string | undefined {
- const paths = files.map(f => f.path.toLowerCase()).join(' ');
-
- switch (category) {
- case 'feature':
- if (/api/.test(paths)) return 'api';
- if (/ui|component|page/.test(paths)) return 'frontend';
- if (/model|database/.test(paths)) return 'backend';
- break;
- case 'bugfix':
- if (/security|auth/.test(paths)) return 'security-fix';
- if (/performance|perf/.test(paths)) return 'performance-fix';
- break;
- case 'infra':
- if (/docker/.test(paths)) return 'containerization';
- if (/ci|cd|workflow/.test(paths)) return 'ci-cd';
- if (/kubernetes|k8s/.test(paths)) return 'kubernetes';
- break;
+ private isRefactoring(hunks: DiffHunk[]): boolean {
+ let totalAdds = 0, totalRemoves = 0;
+ for (const hunk of hunks) { for (const change of hunk.changes) { if (change.type === 'add') totalAdds++; else if (change.type === 'remove') totalRemoves++; } }
+ const ratio = totalAdds > 0 ? totalRemoves / totalAdds : 0;
+ return ratio > 0.7 && ratio < 1.4 && totalAdds > 5;
}
- return undefined;
-}
-
-function generateClassificationReasoning(
- category: string,
- files: DiffFile[],
- categories: Record<string, number>
-): string {
- const total = files.length;
- const parts: string[] = [];
-
- parts.push(`${total} file(s) changed.`);
-
- if (categories.test > 0) {
- parts.push(`${categories.test} test file(s).`);
+ private determineSecondaryClassifications(path: string, hunks: DiffHunk[], primary: DiffClassification['primary']): string[] {
+ const secondary: string[] = [];
+ for (const [type, patterns] of Object.entries(CLASSIFICATION_PATTERNS)) {
+ if (type === primary) continue;
+ for (const pattern of patterns) { if (pattern.test(path)) { secondary.push(type); break; } }
+ }
+ return secondary.slice(0, 3);
}
- if (categories.docs > 0) {
- parts.push(`${categories.docs} documentation file(s).`);
+ private calculateConfidence(path: string, hunks: DiffHunk[], primary: DiffClassification['primary']): number {
+ let confidence = 0.5;
+ for (const patterns of Object.values(CLASSIFICATION_PATTERNS)) { for (const pattern of patterns) { if (pattern.test(path)) { confidence += 0.2; break; } } }
+ const totalChanges = hunks.reduce((sum, h) => sum + h.changes.length, 0);
+ if (totalChanges > 10) confidence += 0.1;
+ if (totalChanges > 50) confidence += 0.1;
+ if (primary !== 'unknown') confidence += 0.1;
+ return Math.min(1, confidence);
}
- const addedCount = files.filter(f => f.status === 'added').length;
- const deletedCount = files.filter(f => f.status === 'deleted').length;
-
- if (addedCount > 0) {
- parts.push(`${addedCount} new file(s) added.`);
+ private determineImpactLevel(path: string, hunks: DiffHunk[]): DiffClassification['impactLevel'] {
+ let score = 0;
+ const lowerPath = path.toLowerCase();
+ for (const [keyword, weight] of Object.entries(IMPACT_KEYWORDS)) { if (lowerPath.includes(keyword)) score = Math.max(score, weight); }
+ const totalChanges = hunks.reduce((sum, h) => sum + h.changes.filter(c => c.type !== 'context').length, 0);
+ if (totalChanges > 100) score = Math.max(score, 2);
+ if (totalChanges > 300) score = Math.max(score, 3);
+ if (score >= 3) return 'critical';
+ if (score >= 2) return 'high';
+ if (score >= 1) return 'medium';
+ return 'low';
}
- if (deletedCount > 0) {
- parts.push(`${deletedCount} file(s) deleted.`);
+ private suggestReviewers(path: string, primary: DiffClassification['primary'], impact: DiffClassification['impactLevel']): string[] {
+ const reviewers: string[] = [];
+ const typeReviewers: Record<string, string[]> = { feature: ['tech-lead', 'product-owner'], bugfix: ['qa-engineer', 'developer'], refactor: ['senior-developer', 'architect'], docs: ['tech-writer', 'developer'], test: ['qa-engineer', 'developer'], config: ['devops', 'tech-lead'], style: ['developer'], unknown: ['developer'] };
+ reviewers.push(...(typeReviewers[primary] || typeReviewers.unknown));
+ if (impact === 'critical' || impact === 'high') reviewers.push('security-reviewer');
+ if (/security|auth/.test(path)) reviewers.push('security-team');
+ if (/database|migration/.test(path)) reviewers.push('dba');
+ return [...new Set(reviewers)].slice(0, 4);
}
- parts.push(`Classified as ${category} based on change patterns.`);
-
- return parts.join(' ');
-}
-
-// ============================================
-// Reviewer Recommendations
-// ============================================
-
-/**
- * Suggest reviewers based on files changed and their history
- */
-export function suggestReviewers(files: DiffFile[], fileRisks: FileRisk[]): string[] {
- const reviewerScores = new Map<string, number>();
-
- for (const file of files) {
- const ext = file.path.match(/\.[a-zA-Z0-9]+$/)?.[0] || '';
- const pathLower = file.path.toLowerCase();
-
- // Add reviewers based on file extension
- const extReviewers = REVIEWER_PATTERNS[ext] || [];
- for (const reviewer of extReviewers) {
- reviewerScores.set(reviewer, (reviewerScores.get(reviewer) || 0) + 1);
- }
-
- // Add reviewers based on path patterns
- for (const [pattern, reviewers] of Object.entries(REVIEWER_PATTERNS)) {
- if (pathLower.includes(pattern)) {
- for (const reviewer of reviewers) {
- reviewerScores.set(reviewer, (reviewerScores.get(reviewer) || 0) + 2);
- }
- }
- }
+ private determineTestingStrategy(path: string, primary: DiffClassification['primary'], impact: DiffClassification['impactLevel']): string[] {
+ const strategies: string[] = [];
+ if (primary !== 'test') strategies.push('unit-tests');
+ if (primary === 'feature') strategies.push('integration-tests');
+ if (impact === 'high' || impact === 'critical') { strategies.push('regression-tests'); strategies.push('e2e-tests'); }
+ if (/api|endpoint|route|handler/.test(path)) strategies.push('api-contract-tests');
+ if (/security|auth|crypto/.test(path)) strategies.push('security-audit');
+ return strategies.slice(0, 5);
}
- // Boost scores for high-risk files
- for (const risk of fileRisks.filter(f => f.risk === 'high-risk' || f.risk === 'critical')) {
- reviewerScores.set('senior-reviewer', (reviewerScores.get('senior-reviewer') || 0) + 3);
- if (risk.reasons.some(r => /security/i.test(r))) {
- reviewerScores.set('security-expert', (reviewerScores.get('security-expert') || 0) + 3);
- }
+ private identifyRiskFactors(path: string, hunks: DiffHunk[], impact: DiffClassification['impactLevel']): string[] {
+ const risks: string[] = [];
+ const totalChanges = hunks.reduce((sum, h) => sum + h.changes.length, 0);
+ if (totalChanges > 200) risks.push('Large change set - increased review time needed');
+ if (impact === 'critical') risks.push('Critical system component - requires careful review');
+ if (impact === 'high') risks.push('High-impact area - monitor after deployment');
+ if (/security|auth/.test(path)) risks.push('Security-sensitive code');
+ if (/database|migration/.test(path)) risks.push('Database changes - ensure backup strategy');
+ if (/config|env/.test(path)) risks.push('Configuration changes - verify all environments');
+ const allContent = hunks.flatMap(h => h.changes.map(c => c.content)).join('\n');
+ if (/TODO|FIXME|HACK/.test(allContent)) risks.push('Contains TODO/FIXME comments');
+ if (/password|secret|key|token/i.test(allContent)) risks.push('Potential secrets in code');
+ return risks.slice(0, 5);
}
- // Sort by score and return top reviewers
- return Array.from(reviewerScores.entries())
- .sort((a, b) => b[1] - a[1])
- .slice(0, 5)
- .map(([reviewer]) => reviewer);
-}
-
-// ============================================
-// Main Analysis Function
-// ============================================
-
-export interface AnalyzeOptions {
- ref?: string;
- cwd?: string;
- useRuVector?: boolean;
-}
-
-/**
- * Perform complete diff analysis
- */
-export async function analyzeDiff(options: AnalyzeOptions = {}): Promise<DiffAnalysisResult> {
- const ref = options.ref || 'HEAD~1';
- const cwd = options.cwd || process.cwd();
-
- // Get diff data
- const diffContent = getGitDiff(ref, cwd);
- const files = getGitDiffNumstat(ref, cwd);
-
- // Try ruvector if available and requested
- if (options.useRuVector !== false) {
- const ruVectorAnalysis = await tryRuVectorAnalysis(diffContent);
- const ruVectorClassify = await tryRuVectorClassify(diffContent);
-
- if (ruVectorAnalysis.available && ruVectorAnalysis.analysis) {
- // Use ruvector results if available
- // This would integrate with ruvector's output format
- }
+ private computeOverallClassification(files: FileDiff[]): DiffClassification {
+ if (files.length === 0) return { primary: 'unknown', secondary: [], confidence: 0, impactLevel: 'low', suggestedReviewers: [], testingStrategy: [], riskFactors: [] };
+ const primaryCounts: Record<string, number> = {};
+ for (const file of files) { const p = file.classification.primary; primaryCounts[p] = (primaryCounts[p] || 0) + 1; }
+ let primary: DiffClassification['primary'] = 'unknown';
+ let maxCount = 0;
+ for (const [type, count] of Object.entries(primaryCounts)) { if (count > maxCount) { maxCount = count; primary = type as DiffClassification['primary']; } }
+ const secondaryCounts: Record<string, number> = {};
+ for (const file of files) { for (const s of file.classification.secondary) { secondaryCounts[s] = (secondaryCounts[s] || 0) + 1; } }
+ const secondary = Object.entries(secondaryCounts).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([type]) => type);
+ const confidence = files.reduce((sum, f) => sum + f.classification.confidence, 0) / files.length;
+ const impactOrder: DiffClassification['impactLevel'][] = ['low', 'medium', 'high', 'critical'];
+ let impactLevel: DiffClassification['impactLevel'] = 'low';
+ for (const file of files) { if (impactOrder.indexOf(file.classification.impactLevel) > impactOrder.indexOf(impactLevel)) impactLevel = file.classification.impactLevel; }
+ const reviewers = [...new Set(files.flatMap(f => f.classification.suggestedReviewers))].slice(0, 5);
+ const testingStrategy = [...new Set(files.flatMap(f => f.classification.testingStrategy))].slice(0, 5);
+ const riskFactors = [...new Set(files.flatMap(f => f.classification.riskFactors))].slice(0, 5);
+ return { primary, secondary, confidence, impactLevel, suggestedReviewers: reviewers, testingStrategy, riskFactors };
}
-
- // Assess each file's risk
- const fileRisks = files.map(assessFileRisk);
-
- // Calculate overall risk
- const risk = assessOverallRisk(files, fileRisks);
-
- // Classify the change type
- const classification = classifyDiff(files);
-
- // Suggest reviewers
- const recommendedReviewers = suggestReviewers(files, fileRisks);
-
- // Generate summary
- const summary = generateSummary(files, risk, classification);
-
- return {
- ref,
- timestamp: new Date().toISOString(),
- files,
- risk,
- classification,
- fileRisks,
- recommendedReviewers,
- summary,
- };
}
-function generateSummary(
- files: DiffFile[],
- risk: DiffRiskAssessment,
- classification: DiffClassification
-): string {
- const parts: string[] = [];
-
- parts.push(`${classification.category.charAt(0).toUpperCase() + classification.category.slice(1)} change`);
-
- if (classification.subcategory) {
- parts.push(`(${classification.subcategory})`);
- }
-
- parts.push(`affecting ${files.length} file(s).`);
- parts.push(`Risk level: ${risk.overall} (score: ${risk.score}/100).`);
-
- if (risk.breakdown.securityConcerns.length > 0) {
- parts.push(`${risk.breakdown.securityConcerns.length} security concern(s) detected.`);
- }
-
- if (risk.breakdown.breakingChanges.length > 0) {
- parts.push(`${risk.breakdown.breakingChanges.length} potential breaking change(s).`);
- }
-
- return parts.join(' ');
+export function createDiffClassifier(config?: Partial<DiffClassifierConfig>): DiffClassifier {
+ return new DiffClassifier(config);
}
-
-// Export utility for CLI
-export const DiffClassifier = {
- analyzeDiff,
- getGitDiff,
- getGitDiffStat,
- getGitDiffNumstat,
- assessFileRisk,
- assessOverallRisk,
- classifyDiff,
- suggestReviewers,
-};
-
-export default DiffClassifier;
diff --git a/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts b/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts
index 38894de7fb..62cb82e300 100644
--- a/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts
+++ b/v3/@claude-flow/cli/src/ruvector/graph-analyzer.ts
@@ -136,12 +136,17 @@ async function loadRuVector(): Promise<IRuVectorGraph | null> {
if (ruVectorLoadAttempted) return ruVectorGraph;
ruVectorLoadAttempted = true;
+ // Use dynamic module names to bypass TypeScript static analysis
+ // These modules are optional and may not be installed
+ const ruvectorModule = 'ruvector';
+ const wasmModule = '@ruvector/wasm';
+
try {
// Try to load ruvector's graph module
- // @ts-expect-error - ruvector types may not be available
- const ruvector = await import('ruvector');
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const ruvector: any = await import(/* webpackIgnore: true */ ruvectorModule).catch(() => null);
- if (ruvector.hooks_graph_mincut && ruvector.hooks_graph_cluster) {
+ if (ruvector && typeof ruvector.hooks_graph_mincut === 'function' && typeof ruvector.hooks_graph_cluster === 'function') {
ruVectorGraph = {
mincut: (nodes, edges) => ruvector.hooks_graph_mincut(nodes, edges),
louvain: (nodes, edges) => ruvector.hooks_graph_cluster(nodes, edges),
@@ -151,10 +156,10 @@ async function loadRuVector(): Promise<IRuVectorGraph | null> {
} catch {
// Try alternative import paths
try {
- // @ts-expect-error - @ruvector/wasm types may not be available
- const wasmModule = await import('@ruvector/wasm');
- if (wasmModule.GraphAnalyzer) {
- const analyzer = new wasmModule.GraphAnalyzer();
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const wasm: any = await import(/* webpackIgnore: true */ wasmModule).catch(() => null);
+ if (wasm && wasm.GraphAnalyzer) {
+ const analyzer = new wasm.GraphAnalyzer();
ruVectorGraph = {
mincut: (nodes, edges) => analyzer.mincut(nodes, edges),
louvain: (nodes, edges) => analyzer.louvain(nodes, edges),
@@ -176,7 +181,7 @@ async function loadRuVector(): Promise<IRuVectorGraph | null> {
/**
* Extract imports from TypeScript/JavaScript file
*/
-function extractImports(content: string, filePath: string): Array<{ path: string; type: GraphEdge['type'] }> {
+function extractImports(content: string, _filePath: string): Array<{ path: string; type: GraphEdge['type'] }> {
const imports: Array<{ path: string; type: GraphEdge['type'] }> = [];
// ES6 import statements
@@ -459,8 +464,8 @@ function estimateComplexity(content: string): number {
// ============================================================================
/**
- * Karger's MinCut algorithm (fallback when ruvector not available)
- * Randomized algorithm that finds minimum cut with high probability
+ * Stoer-Wagner MinCut algorithm (fallback when ruvector not available)
+ * Finds minimum cut with deterministic result
*/
function fallbackMinCut(
nodes: string[],
@@ -480,9 +485,6 @@ function fallbackMinCut(
};
}
- // Use Stoer-Wagner for deterministic result (simplified version)
- // This is a simplified MinCut that finds cuts using maximum adjacency ordering
-
// Build adjacency map with weights
const adj = new Map<string, Map<string, number>>();
for (const node of nodes) {
@@ -514,9 +516,9 @@ function fallbackMinCut(
let maxNode = '';
let maxConn = -1;
- for (const node of remaining) {
+ for (const node of Array.from(remaining)) {
let conn = 0;
- for (const inNode of inSet) {
+ for (const inNode of Array.from(inSet)) {
conn += adj.get(node)?.get(inNode) || 0;
}
if (conn > maxConn) {
@@ -536,7 +538,7 @@ function fallbackMinCut(
let cutValue = 0;
const cutEdges: Array<[string, string]> = [];
- for (const inNode of inSet) {
+ for (const inNode of Array.from(inSet)) {
const weight = adj.get(lastNode)?.get(inNode) || 0;
if (weight > 0) {
cutValue += weight;
@@ -631,7 +633,7 @@ function fallbackLouvain(
const degree = new Map<string, number>();
for (const node of nodes) {
let d = 0;
- for (const [, w] of adj.get(node)!) {
+ for (const [, w] of Array.from(adj.get(node)!.entries())) {
d += w;
}
degree.set(node, d);
@@ -654,7 +656,7 @@ function fallbackLouvain(
// Calculate modularity gain for moving to each neighbor's community
const communityWeights = new Map<number, number>();
- for (const [neighbor, weight] of nodeAdj) {
+ for (const [neighbor, weight] of Array.from(nodeAdj.entries())) {
const neighborCommunity = community.get(neighbor)!;
communityWeights.set(
neighborCommunity,
@@ -664,14 +666,14 @@ function fallbackLouvain(
// Calculate community totals
const communityTotal = new Map<number, number>();
- for (const [n, c] of community) {
+ for (const [n, c] of Array.from(community.entries())) {
communityTotal.set(c, (communityTotal.get(c) || 0) + (degree.get(n) || 0));
}
let bestCommunity = currentCommunity;
let bestGain = 0;
- for (const [targetCommunity, edgeWeight] of communityWeights) {
+ for (const [targetCommunity, edgeWeight] of Array.from(communityWeights.entries())) {
if (targetCommunity === currentCommunity) continue;
// Calculate modularity gain
@@ -698,7 +700,7 @@ function fallbackLouvain(
// Collect communities
const communityMembers = new Map<number, string[]>();
- for (const [node, comm] of community) {
+ for (const [node, comm] of Array.from(community.entries())) {
if (!communityMembers.has(comm)) {
communityMembers.set(comm, []);
}
@@ -708,7 +710,7 @@ function fallbackLouvain(
// Renumber communities
const communities: Array<{ id: number; members: string[] }> = [];
let id = 0;
- for (const [, members] of communityMembers) {
+ for (const members of Array.from(communityMembers.values())) {
communities.push({ id: id++, members });
}
@@ -743,7 +745,7 @@ export function detectCircularDependencies(graph: DependencyGraph): CircularDepe
// Build adjacency list
const adjList = new Map<string, string[]>();
- for (const node of graph.nodes.keys()) {
+ for (const node of Array.from(graph.nodes.keys())) {
adjList.set(node, []);
}
for (const edge of graph.edges) {
@@ -781,7 +783,7 @@ export function detectCircularDependencies(graph: DependencyGraph): CircularDepe
path.pop();
}
- for (const node of graph.nodes.keys()) {
+ for (const node of Array.from(graph.nodes.keys())) {
if (!visited.has(node)) {
dfs(node);
}
@@ -790,7 +792,7 @@ export function detectCircularDependencies(graph: DependencyGraph): CircularDepe
return cycles;
}
-function getCycleSeverity(cycle: string[], graph: DependencyGraph): 'low' | 'medium' | 'high' {
+function getCycleSeverity(cycle: string[], _graph: DependencyGraph): 'low' | 'medium' | 'high' {
// High severity if cycle involves many files or core modules
if (cycle.length > 5) return 'high';
if (cycle.some(n => n.includes('index') || n.includes('core'))) return 'high';
@@ -884,14 +886,16 @@ export async function analyzeMinCutBoundaries(
return boundaries;
}
-function generateBoundarySuggestion(partition1: string[], partition2: string[], graph: DependencyGraph): string {
+function generateBoundarySuggestion(partition1: string[], partition2: string[], _graph: DependencyGraph): string {
// Analyze the partitions to suggest organization
- const p1Dirs = new Set(partition1.map(p => dirname(p)).filter(d => d !== '.'));
- const p2Dirs = new Set(partition2.map(p => dirname(p)).filter(d => d !== '.'));
-
- if (p1Dirs.size === 1 && p2Dirs.size === 1) {
- const dir1 = Array.from(p1Dirs)[0];
- const dir2 = Array.from(p2Dirs)[0];
+ const p1Dirs = partition1.map(p => dirname(p)).filter(d => d !== '.');
+ const p2Dirs = partition2.map(p => dirname(p)).filter(d => d !== '.');
+ const p1DirsSet = new Set(p1Dirs);
+ const p2DirsSet = new Set(p2Dirs);
+
+ if (p1DirsSet.size === 1 && p2DirsSet.size === 1) {
+ const dir1 = p1Dirs[0];
+ const dir2 = p2Dirs[0];
return `Natural boundary detected between ${dir1}/ and ${dir2}/. These could be separate packages.`;
}
@@ -990,7 +994,7 @@ export async function analyzeGraph(
const edgeCount = graph.edges.length;
const degrees = new Map<string, number>();
- for (const node of graph.nodes.keys()) {
+ for (const node of Array.from(graph.nodes.keys())) {
degrees.set(node, 0);
}
for (const edge of graph.edges) {
@@ -1019,7 +1023,7 @@ export async function analyzeGraph(
}
}
- for (const node of graph.nodes.keys()) {
+ for (const node of Array.from(graph.nodes.keys())) {
if (!visited.has(node)) {
componentCount++;
dfs(node);
@@ -1105,7 +1109,7 @@ export function exportToDot(
// Output nodes
lines.push(' // Nodes');
- for (const [id, node] of graph.nodes) {
+ for (const [id, node] of Array.from(graph.nodes.entries())) {
const attrs: string[] = [];
if (options.includeLabels !== false) {
diff --git a/v3/@claude-flow/cli/src/ruvector/index.ts b/v3/@claude-flow/cli/src/ruvector/index.ts
index d6b30a4be0..394890658a 100644
--- a/v3/@claude-flow/cli/src/ruvector/index.ts
+++ b/v3/@claude-flow/cli/src/ruvector/index.ts
@@ -13,9 +13,43 @@
export { QLearningRouter, createQLearningRouter, type QLearningRouterConfig, type RouteDecision } from './q-learning-router.js';
export { ASTAnalyzer, createASTAnalyzer, type ASTAnalysis, type ASTNode, type ASTAnalyzerConfig } from './ast-analyzer.js';
-export { DiffClassifier, createDiffClassifier, type DiffClassification, type DiffHunk, type DiffClassifierConfig } from './diff-classifier.js';
-export { CoverageRouter, createCoverageRouter, type CoverageReport, type CoverageRouteResult, type CoverageRouterConfig } from './coverage-router.js';
-export { GraphAnalyzer, createGraphAnalyzer, type GraphBoundary, type DependencyGraph, type GraphAnalyzerConfig } from './graph-analyzer.js';
+export {
+ DiffClassifier,
+ createDiffClassifier,
+ type DiffClassification,
+ type DiffHunk,
+ type DiffChange,
+ type FileDiff,
+ type DiffAnalysis,
+ type DiffClassifierConfig,
+} from './diff-classifier.js';
+export {
+ CoverageRouter,
+ createCoverageRouter,
+ type CoverageRouterConfig,
+ type FileCoverage,
+ type CoverageReport,
+ type CoverageRouteResult,
+} from './coverage-router.js';
+export { coverageRouterTools, hooksCoverageRoute, hooksCoverageSuggest, hooksCoverageGaps } from './coverage-tools.js';
+export {
+ buildDependencyGraph,
+ analyzeGraph,
+ analyzeMinCutBoundaries,
+ analyzeModuleCommunities,
+ detectCircularDependencies,
+ exportToDot,
+ loadRuVector,
+ fallbackMinCut,
+ fallbackLouvain,
+ type GraphNode,
+ type GraphEdge,
+ type DependencyGraph,
+ type MinCutBoundary,
+ type ModuleCommunity,
+ type CircularDependency,
+ type GraphAnalysisResult,
+} from './graph-analyzer.js';
/**
* Check if ruvector packages are available