π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
Checkpoint: File edits
rUvc4bdacc741fd
diff --git a/v3/@claude-flow/cli/src/init/claudemd-generator.ts b/v3/@claude-flow/cli/src/init/claudemd-generator.tsindex c741c76408..b65e84a9c5 100644--- a/v3/@claude-flow/cli/src/init/claudemd-generator.ts+++ b/v3/@claude-flow/cli/src/init/claudemd-generator.ts@@ -1,231 +1,126 @@/*** CLAUDE.md Generator- * Generates project-specific Claude Code configuration with V3 swarm guidance+ * Generates enforceable, analyzer-optimized Claude Code configuration+ * with template variants for different usage patterns.+ *+ * Templates: minimal | standard | full | security | performance | solo+ * All templates use bullet-format rules with imperative keywords for enforceability.*/-import type { InitOptions } from './types.js';+import type { InitOptions, ClaudeMdTemplate } from './types.js';-/**- * Generate CLAUDE.md content based on init options- */-export function generateClaudeMd(options: InitOptions): string {- const topology = options.runtime.topology;- const maxAgents = options.runtime.maxAgents;- const memoryBackend = options.runtime.memoryBackend;+// --- Section Generators (each returns enforceable markdown) ---- return `# Claude Code Configuration - Claude Flow V3+function behavioralRules(): string {+ return `## Behavioral Rules (Always Enforced)-## π¨ AUTOMATIC SWARM ORCHESTRATION+- Do what has been asked; nothing more, nothing less+- 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 unless explicitly requested+- NEVER save working files, text/mds, or tests to the root folder+- Never continuously check status after spawning a swarm β wait for results+- ALWAYS read a file before editing it+- NEVER commit secrets, credentials, or .env files`;+}-**When starting work on complex tasks, Claude Code MUST automatically:**+function fileOrganization(): string {+ return `## File Organization-1. **Initialize the swarm** using CLI tools via Bash-2. **Spawn concurrent agents** using Claude Code's Task tool-3. **Coordinate via hooks** and memory+- NEVER save to root folder β use the directories below+- Use \`/src\` for source code files+- Use \`/tests\` for test files+- Use \`/docs\` for documentation and markdown files+- Use \`/config\` for configuration files+- Use \`/scripts\` for utility scripts+- Use \`/examples\` for example code`;+}-### π¨ CRITICAL: CLI + Task Tool in SAME Message+function projectArchitecture(options: InitOptions): string {+ return `## Project Architecture-**When user says "spawn swarm" or requests complex work, Claude Code MUST in ONE message:**-1. Call CLI tools via Bash to initialize coordination-2. **IMMEDIATELY** call Task tool to spawn REAL working agents-3. Both CLI and Task calls must be in the SAME response+- Follow Domain-Driven Design with bounded contexts+- Keep files under 500 lines+- Use typed interfaces for all public APIs+- Prefer TDD London School (mock-first) for new code+- Use event sourcing for state changes+- Ensure input validation at system boundaries-**CLI coordinates, Task tool agents do the actual work!**+### Project Config-### π€ INTELLIGENT 3-TIER MODEL ROUTING (ADR-026)+- **Topology**: ${options.runtime.topology}+- **Max Agents**: ${options.runtime.maxAgents}+- **Memory**: ${options.runtime.memoryBackend}+- **HNSW**: ${options.runtime.enableHNSW ? 'Enabled' : 'Disabled'}+- **Neural**: ${options.runtime.enableNeural ? 'Enabled' : 'Disabled'}`;+}-**The routing system has 3 tiers for optimal cost/performance:**+function concurrencyRules(): string {+ return `## Concurrency: 1 MESSAGE = ALL RELATED OPERATIONS-| Tier | Handler | Latency | Cost | Use Cases |-|------|---------|---------|------|-----------|-| **1** | Agent Booster | <1ms | $0 | Simple transforms (varβconst, add-types, remove-console) |-| **2** | Haiku | ~500ms | $0.0002 | Simple tasks, bug fixes, low complexity |-| **3** | Sonnet/Opus | 2-5s | $0.003-$0.015 | Architecture, security, complex reasoning |+- All operations MUST be concurrent/parallel in a single message+- Use Claude Code's Task tool for spawning agents, not just MCP+- ALWAYS batch ALL todos in ONE TodoWrite call (5-10+ minimum)+- ALWAYS spawn ALL agents in ONE message with full instructions via Task tool+- ALWAYS batch ALL file reads/writes/edits in ONE message+- ALWAYS batch ALL Bash commands in ONE message`;+}-**Before spawning agents, get routing recommendation:**-\`\`\`bash-npx @claude-flow/cli@latest hooks pre-task --description "[task description]"-\`\`\`+function swarmOrchestration(): string {+ return `## Swarm Orchestration-**When you see these recommendations:**+- MUST initialize the swarm using CLI tools when starting complex tasks+- MUST spawn concurrent agents using Claude Code's Task tool+- Never use CLI tools alone for execution β Task tool agents do the actual work+- MUST call CLI tools AND Task tool in ONE message for complex work-1. \`[AGENT_BOOSTER_AVAILABLE]\` β Skip LLM entirely, use Edit tool directly- - Intent types: \`var-to-const\`, \`add-types\`, \`add-error-handling\`, \`async-await\`, \`add-logging\`, \`remove-console\`+### 3-Tier Model Routing (ADR-026)-2. \`[TASK_MODEL_RECOMMENDATION] Use model="X"\` β Use that model in Task tool:-\`\`\`javascript-Task({- prompt: "...",- subagent_type: "coder",- model: "haiku" // β USE THE RECOMMENDED MODEL (haiku/sonnet/opus)-})-\`\`\`+| Tier | Handler | Latency | Cost | Use Cases |+|------|---------|---------|------|-----------|+| **1** | Agent Booster (WASM) | <1ms | $0 | Simple transforms (varβconst, add types) β Skip LLM |+| **2** | Haiku | ~500ms | $0.0002 | Simple tasks, low complexity (<30%) |+| **3** | Sonnet/Opus | 2-5s | $0.003-0.015 | Complex reasoning, architecture, security (>30%) |-**Benefits:** 75% cost reduction, 352x faster for Tier 1 tasks+- Always check for \`[AGENT_BOOSTER_AVAILABLE]\` or \`[TASK_MODEL_RECOMMENDATION]\` before spawning agents+- Use Edit tool directly when \`[AGENT_BOOSTER_AVAILABLE]\``;+}----+function antiDriftConfig(): string {+ return `## Swarm Configuration & Anti-Drift-### π‘οΈ Anti-Drift Config (PREFERRED)+- ALWAYS use hierarchical topology for coding swarms+- Keep maxAgents at 6-8 for tight coordination+- Use specialized strategy for clear role boundaries+- Use \`raft\` consensus for hive-mind (leader maintains authoritative state)+- Run frequent checkpoints via \`post-task\` hooks+- Keep shared memory namespace for all agents-**Use this to prevent agent drift:**\`\`\`bash-# Small teams (6-8 agents) - use hierarchical for tight controlnpx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized+\`\`\``;+}-# Large teams (10-15 agents) - use hierarchical-mesh for V3 queen + peer communication-npx @claude-flow/cli@latest swarm init --topology hierarchical-mesh --max-agents 15 --strategy specialized-\`\`\`--**Valid Topologies:**-- \`hierarchical\` - Queen controls workers directly (anti-drift for small teams)-- \`hierarchical-mesh\` - V3 queen + peer communication (recommended for 10+ agents)-- \`mesh\` - Fully connected peer network-- \`ring\` - Circular communication pattern-- \`star\` - Central coordinator with spokes-- \`hybrid\` - Dynamic topology switching--**Anti-Drift Guidelines:**-- **hierarchical**: Coordinator catches divergence-- **max-agents 6-8**: Smaller team = less drift-- **specialized**: Clear roles, no overlap-- **consensus**: raft (leader maintains state)-----+function autoStartProtocol(): string {+ return `## Swarm Protocols & Routing-### π Auto-Start Swarm Protocol (Background Execution)+### Auto-Start Swarm Protocol-When the user requests a complex task, **spawn agents in background and WAIT for completion:**+When the user requests a complex task, spawn agents in background and WAIT:\`\`\`javascript-// STEP 1: Initialize swarm coordination (anti-drift config)+// STEP 1: Initialize swarm coordinationBash("npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized")// STEP 2: Spawn ALL agents IN BACKGROUND in a SINGLE message-// Use run_in_background: true so agents work concurrently-Task({- prompt: "Research requirements, analyze codebase patterns, store findings in memory",- subagent_type: "researcher",- description: "Research phase",- run_in_background: true // β CRITICAL: Run in background-})-Task({- prompt: "Design architecture based on research. Document decisions.",- subagent_type: "system-architect",- description: "Architecture phase",- run_in_background: true-})-Task({- prompt: "Implement the solution following the design. Write clean code.",- subagent_type: "coder",- description: "Implementation phase",- run_in_background: true-})-Task({- prompt: "Write comprehensive tests for the implementation.",- subagent_type: "tester",- description: "Testing phase",- run_in_background: true-})-Task({- prompt: "Review code quality, security, and best practices.",- subagent_type: "reviewer",- description: "Review phase",- run_in_background: true-})--// STEP 3: WAIT - Tell user agents are working, then STOP-// Say: "I've spawned 5 agents to work on this in parallel. They'll report back when done."-// DO NOT check status repeatedly. Just wait for user or agent responses.-\`\`\`--### βΈοΈ CRITICAL: Spawn and Wait Pattern--**After spawning background agents:**--1. **TELL USER** - "I've spawned X agents working in parallel on: [list tasks]"-2. **STOP** - Do not continue with more tool calls-3. **WAIT** - Let the background agents complete their work-4. **RESPOND** - When agents return results, review and synthesize--**Example response after spawning:**+Task({prompt: "Research requirements...", subagent_type: "researcher", run_in_background: true})+Task({prompt: "Design architecture...", subagent_type: "system-architect", run_in_background: true})+Task({prompt: "Implement solution...", subagent_type: "coder", run_in_background: true})+Task({prompt: "Write tests...", subagent_type: "tester", run_in_background: true})+Task({prompt: "Review code quality...", subagent_type: "reviewer", run_in_background: true})\`\`\`-I've launched 5 concurrent agents to work on this:-- π Researcher: Analyzing requirements and codebase-- ποΈ Architect: Designing the implementation approach-- π» Coder: Implementing the solution-- π§ͺ Tester: Writing tests-- π Reviewer: Code review and security check--They're working in parallel. I'll synthesize their results when they complete.-\`\`\`--### π« DO NOT:-- Continuously check swarm status-- Poll TaskOutput repeatedly-- Add more tool calls after spawning-- Ask "should I check on the agents?"--### β DO:-- Spawn all agents in ONE message-- Tell user what's happening-- Wait for agent results to arrive-- Synthesize results when they return--## π§ AUTO-LEARNING PROTOCOL--### Before Starting Any Task-\`\`\`bash-# 1. Search memory for relevant patterns from past successes-Bash("npx @claude-flow/cli@latest memory search --query '[task keywords]' --namespace patterns")--# 2. Check if similar task was done before-Bash("npx @claude-flow/cli@latest memory search --query '[task type]' --namespace tasks")--# 3. Load learned optimizations-Bash("npx @claude-flow/cli@latest hooks route --task '[task description]'")-\`\`\`--### After Completing Any Task Successfully-\`\`\`bash-# 1. Store successful pattern for future reference-Bash("npx @claude-flow/cli@latest memory store --namespace patterns --key '[pattern-name]' --value '[what worked]'")--# 2. Train neural patterns on the successful approach-Bash("npx @claude-flow/cli@latest hooks post-edit --file '[main-file]' --train-neural true")--# 3. Record task completion with metrics-Bash("npx @claude-flow/cli@latest hooks post-task --task-id '[id]' --success true --store-results true")--# 4. Trigger optimization worker if performance-related-Bash("npx @claude-flow/cli@latest hooks worker dispatch --trigger optimize")-\`\`\`--### Continuous Improvement Triggers--| Trigger | Worker | When to Use |-|---------|--------|-------------|-| After major refactor | \`optimize\` | Performance optimization |-| After adding features | \`testgaps\` | Find missing test coverage |-| After security changes | \`audit\` | Security analysis |-| After API changes | \`document\` | Update documentation |-| Every 5+ file changes | \`map\` | Update codebase map |-| Complex debugging | \`deepdive\` | Deep code analysis |--### Memory-Enhanced Development--**ALWAYS check memory before:**-- Starting a new feature (search for similar implementations)-- Debugging an issue (search for past solutions)-- Refactoring code (search for learned patterns)-- Performance work (search for optimization strategies)-**ALWAYS store in memory after:**-- Solving a tricky bug (store the solution pattern)-- Completing a feature (store the approach)-- Finding a performance fix (store the optimization)-- Discovering a security issue (store the vulnerability pattern)--### π Agent Routing (Anti-Drift)+### Agent Routing| Code | Task | Agents ||------|------|--------|@@ -234,270 +129,187 @@ Bash("npx @claude-flow/cli@latest hooks worker dispatch --trigger optimize")| 5 | Refactor | coordinator, architect, coder, reviewer || 7 | Performance | coordinator, perf-engineer, coder || 9 | Security | coordinator, security-architect, auditor |-| 11 | Docs | researcher, api-docs |--**Codes 1-9: hierarchical/specialized (anti-drift). Code 11: mesh/balanced**--### π― 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--**ABSOLUTE RULES**:-1. ALL operations MUST be concurrent/parallel in a single message-2. **NEVER save working files, text/mds and tests to the root folder**-3. ALWAYS organize files in appropriate subdirectories-4. **USE CLAUDE CODE'S TASK TOOL** for spawning agents concurrently, not just MCP--### β‘ GOLDEN RULE: "1 MESSAGE = ALL RELATED OPERATIONS"--**MANDATORY PATTERNS:**-- **TodoWrite**: ALWAYS batch ALL todos in ONE call (5-10+ todos minimum)-- **Task tool (Claude Code)**: ALWAYS spawn ALL agents in ONE message with full instructions-- **File operations**: ALWAYS batch ALL reads/writes/edits in ONE message-- **Bash commands**: ALWAYS batch ALL terminal operations in ONE message-- **Memory operations**: ALWAYS batch ALL memory store/retrieve in ONE message--### π File Organization Rules--**NEVER save to root folder. Use these directories:**-- \`/src\` - Source code files-- \`/tests\` - Test files-- \`/docs\` - Documentation and markdown files-- \`/config\` - Configuration files-- \`/scripts\` - Utility scripts-- \`/examples\` - Example code--## Project Config (Anti-Drift Defaults)--- **Topology**: hierarchical (prevents drift)-- **Max Agents**: 8 (smaller = less drift)-- **Strategy**: specialized (clear roles)-- **Consensus**: raft-- **Memory**: ${memoryBackend}-- **HNSW**: ${options.runtime.enableHNSW ? 'Enabled' : 'Disabled'}-- **Neural**: ${options.runtime.enableNeural ? 'Enabled' : 'Disabled'}-## π V3 CLI Commands (26 Commands, 140+ Subcommands)+### Task Complexity Detection-### Core Commands+- AUTO-INVOKE SWARM when task involves: 3+ files, new features, cross-module refactoring, API changes, security, or performance work+- SKIP SWARM for: single file edits, simple bug fixes (1-2 lines), documentation updates, configuration changes`;+}-| 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 |-| \`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+function executionRules(): string {+ return `## Swarm Execution Rules++- ALWAYS use \`run_in_background: true\` for all agent Task calls+- ALWAYS put ALL agent Task calls in ONE message for parallel execution+- After spawning, STOP β do NOT add more tool calls or check status+- Never poll TaskOutput or check swarm status β trust agents to return+- When agent results arrive, review ALL results before proceeding`;+}++function cliCommandsTable(): string {+ return `## V3 CLI Commands++### Core 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 |-| \`doctor\` | 1 | System diagnostics with health checks |-| \`completions\` | 4 | Shell completions (bash, zsh, fish, powershell) |+| \`init\` | 4 | Project initialization |+| \`agent\` | 8 | Agent lifecycle management |+| \`swarm\` | 6 | Multi-agent swarm coordination |+| \`memory\` | 11 | AgentDB memory with HNSW search |+| \`task\` | 6 | Task creation and lifecycle |+| \`session\` | 7 | Session state management |+| \`hooks\` | 17 | Self-learning hooks + 12 workers |+| \`hive-mind\` | 6 | Byzantine fault-tolerant consensus |### Quick CLI Examples\`\`\`bash-# Initialize projectnpx @claude-flow/cli@latest init --wizard--# Start daemon with background workers-npx @claude-flow/cli@latest daemon start--# Spawn an agentnpx @claude-flow/cli@latest agent spawn -t coder --name my-coder--# Initialize swarmnpx @claude-flow/cli@latest swarm init --v3-mode--# Search memory (HNSW-indexed)npx @claude-flow/cli@latest memory search --query "authentication patterns"--# System diagnosticsnpx @claude-flow/cli@latest doctor --fix+\`\`\``;+}-# Security scan-npx @claude-flow/cli@latest security scan --depth full--# Performance benchmark-npx @claude-flow/cli@latest performance benchmark --suite all-\`\`\`--## π Available Agents (60+ Types)+function agentTypes(): string {+ return `## Available Agents (60+ Types)### Core Development\`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\`-### V3 Specialized Agents+### Specialized\`security-architect\`, \`security-auditor\`, \`memory-specialist\`, \`performance-engineer\`-### π @claude-flow/security-CVE remediation, input validation, path security:-- \`InputValidator\` - Zod validation-- \`PathValidator\` - Traversal prevention-- \`SafeExecutor\` - Injection protection-### Swarm Coordination-\`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\`, \`collective-intelligence-coordinator\`, \`swarm-memory-manager\`--### Consensus & Distributed-\`byzantine-coordinator\`, \`raft-manager\`, \`gossip-coordinator\`, \`consensus-builder\`, \`crdt-synchronizer\`, \`quorum-manager\`, \`security-manager\`--### Performance & Optimization-\`perf-analyzer\`, \`performance-benchmarker\`, \`task-orchestrator\`, \`memory-coordinator\`, \`smart-agent\`+\`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\`### GitHub & Repository-\`github-modes\`, \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\`, \`workflow-automation\`, \`project-board-sync\`, \`repo-architect\`, \`multi-repo-swarm\`+\`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\`### SPARC Methodology-\`sparc-coord\`, \`sparc-coder\`, \`specification\`, \`pseudocode\`, \`architecture\`, \`refinement\`--### Specialized Development-\`backend-dev\`, \`mobile-dev\`, \`ml-developer\`, \`cicd-engineer\`, \`api-docs\`, \`system-architect\`, \`code-analyzer\`, \`base-template-generator\`--### Testing & Validation-\`tdd-london-swarm\`, \`production-validator\`--## πͺ V3 Hooks System (27 Hooks + 12 Workers)--### All Available Hooks--| Hook | Description | Key Options |-|------|-------------|-------------|-| \`pre-edit\` | Get context before editing files | \`--file\`, \`--operation\` |-| \`post-edit\` | Record editing outcome for learning | \`--file\`, \`--success\`, \`--train-neural\` |-| \`pre-command\` | Assess risk before commands | \`--command\`, \`--validate-safety\` |-| \`post-command\` | Record command execution outcome | \`--command\`, \`--track-metrics\` |-| \`pre-task\` | Record task start, get agent suggestions | \`--description\`, \`--coordinate-swarm\` |-| \`post-task\` | Record task completion for learning | \`--task-id\`, \`--success\`, \`--store-results\` |-| \`session-start\` | Start/restore session (v2 compat) | \`--session-id\`, \`--auto-configure\` |-| \`session-end\` | End session and persist state | \`--generate-summary\`, \`--export-metrics\` |-| \`session-restore\` | Restore a previous session | \`--session-id\`, \`--latest\` |-| \`route\` | Route task to optimal agent | \`--task\`, \`--context\`, \`--top-k\` |-| \`route-task\` | (v2 compat) Alias for route | \`--task\`, \`--auto-swarm\` |-| \`explain\` | Explain routing decision | \`--topic\`, \`--detailed\` |-| \`pretrain\` | Bootstrap intelligence from repo | \`--model-type\`, \`--epochs\` |-| \`build-agents\` | Generate optimized agent configs | \`--agent-types\`, \`--focus\` |-| \`metrics\` | View learning metrics dashboard | \`--v3-dashboard\`, \`--format\` |-| \`transfer\` | Transfer patterns via IPFS registry | \`store\`, \`from-project\` |-| \`list\` | List all registered hooks | \`--format\` |-| \`intelligence\` | RuVector intelligence system | \`trajectory-*\`, \`pattern-*\`, \`stats\` |-| \`worker\` | Background worker management | \`list\`, \`dispatch\`, \`status\`, \`detect\` |-| \`progress\` | Check V3 implementation progress | \`--detailed\`, \`--format\` |-| \`statusline\` | Generate dynamic statusline | \`--json\`, \`--compact\`, \`--no-color\` |-| \`coverage-route\` | Route based on test coverage gaps | \`--task\`, \`--path\` |-| \`coverage-suggest\` | Suggest coverage improvements | \`--path\` |-| \`coverage-gaps\` | List coverage gaps with priorities | \`--format\`, \`--limit\` |-| \`pre-bash\` | (v2 compat) Alias for pre-command | Same as pre-command |-| \`post-bash\` | (v2 compat) Alias for post-command | Same as post-command |+\`sparc-coord\`, \`sparc-coder\`, \`specification\`, \`pseudocode\`, \`architecture\``;+}++function hooksSystem(): string {+ return `## Hooks System (27 Hooks + 12 Workers)++### Essential Hooks++| Hook | Description |+|------|-------------|+| \`pre-task\` / \`post-task\` | Task lifecycle with learning |+| \`pre-edit\` / \`post-edit\` | File editing with neural training |+| \`session-start\` / \`session-end\` | Session state persistence |+| \`route\` | Route task to optimal agent |+| \`intelligence\` | RuVector intelligence system |+| \`worker\` | Background worker management |### 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 |+| \`testgaps\` | normal | Test coverage 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 hooksnpx @claude-flow/cli@latest hooks pre-task --description "[task]"npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true-npx @claude-flow/cli@latest hooks post-edit --file "[file]" --train-neural true+npx @claude-flow/cli@latest hooks worker dispatch --trigger audit+\`\`\``;+}-# Session management-npx @claude-flow/cli@latest hooks session-start --session-id "[id]"-npx @claude-flow/cli@latest hooks session-end --export-metrics true-npx @claude-flow/cli@latest hooks session-restore --session-id "[id]"+function learningProtocol(): string {+ return `## Auto-Learning Protocol-# Intelligence routing-npx @claude-flow/cli@latest hooks route --task "[task]"-npx @claude-flow/cli@latest hooks explain --topic "[topic]"+### Before Starting Any Task+\`\`\`bash+npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns+npx @claude-flow/cli@latest hooks route --task "[task description]"+\`\`\`-# Neural learning-npx @claude-flow/cli@latest hooks pretrain --model-type moe --epochs 10-npx @claude-flow/cli@latest hooks build-agents --agent-types coder,tester+### After Completing Any Task Successfully+\`\`\`bash+npx @claude-flow/cli@latest memory store --namespace patterns --key "[pattern-name]" --value "[what worked]"+npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true+\`\`\`-# Background workers-npx @claude-flow/cli@latest hooks worker list-npx @claude-flow/cli@latest hooks worker dispatch --trigger audit-npx @claude-flow/cli@latest hooks worker status+- ALWAYS check memory before starting new features, debugging, or refactoring+- ALWAYS store patterns in memory after solving bugs, completing features, or finding optimizations`;+}-# Coverage-aware routing-npx @claude-flow/cli@latest hooks coverage-gaps --format table-npx @claude-flow/cli@latest hooks coverage-route --task "[task]"+function memoryCommands(): string {+ return `## Memory Commands Reference-# Statusline (for Claude Code integration)-npx @claude-flow/cli@latest hooks statusline-npx @claude-flow/cli@latest hooks statusline --json-\`\`\`+\`\`\`bash+# Store (REQUIRED: --key, --value; OPTIONAL: --namespace, --ttl, --tags)+npx @claude-flow/cli@latest memory store --key "pattern-auth" --value "JWT with refresh" --namespace patterns++# Search (REQUIRED: --query; OPTIONAL: --namespace, --limit, --threshold)+npx @claude-flow/cli@latest memory search --query "authentication patterns"-## π Migration (V2 to V3)+# List (OPTIONAL: --namespace, --limit)+npx @claude-flow/cli@latest memory list --namespace patterns --limit 10+# Retrieve (REQUIRED: --key; OPTIONAL: --namespace)+npx @claude-flow/cli@latest memory retrieve --key "pattern-auth" --namespace patterns+\`\`\``;+}++function securitySection(): string {+ return `## Security Protocol++- NEVER hardcode API keys, secrets, or credentials in source files+- NEVER commit .env files or any file containing secrets+- Always validate all user input at system boundaries using Zod schemas+- Always sanitize file paths to prevent directory traversal attacks+- Always use parameterized queries β never concatenate SQL strings+- Run security audit after any authentication or authorization changes++### Security Scanning\`\`\`bash-# Check migration status-npx @claude-flow/cli@latest migrate status+npx @claude-flow/cli@latest security scan --depth full+npx @claude-flow/cli@latest security audit --report+npx @claude-flow/cli@latest security cve --check+\`\`\`++### Security Agents+- \`security-architect\` β threat modeling, architecture review+- \`security-auditor\` β code audit, vulnerability detection+- Use agent routing code 9 (hierarchical/specialized) for security tasks`;+}-# Run migration with backup-npx @claude-flow/cli@latest migrate run --backup+function performanceSection(): string {+ return `## Performance Optimization Protocol-# Rollback if needed-npx @claude-flow/cli@latest migrate rollback+- Always run benchmarks before and after performance changes+- Always profile before optimizing β never guess at bottlenecks+- Prefer algorithmic improvements over micro-optimizations+- Keep HNSW search within 150x-12,500x faster target+- Keep memory reduction within 50-75% target with quantization-# Validate migration-npx @claude-flow/cli@latest migrate validate+### Performance Tooling+\`\`\`bash+npx @claude-flow/cli@latest performance benchmark --suite all+npx @claude-flow/cli@latest performance profile --target "[component]"+npx @claude-flow/cli@latest performance metrics --format table\`\`\`-## π§ Intelligence System (RuVector)+### Performance Agents+- \`performance-engineer\` β profiling, benchmarking, optimization+- \`perf-analyzer\` β bottleneck detection, analysis+- Use agent routing code 7 (hierarchical/specialized) for performance tasks`;+}++function intelligenceSystem(): string {+ return `## Intelligence System (RuVector)-V3 includes the RuVector Intelligence System:- **SONA**: Self-Optimizing Neural Architecture (<0.05ms adaptation)-- **MoE**: Mixture of Experts for specialized routing- **HNSW**: 150x-12,500x faster pattern search- **EWC++**: Elastic Weight Consolidation (prevents forgetting)- **Flash Attention**: 2.49x-7.47x speedup@@ -506,311 +318,179 @@ The 4-step intelligence pipeline:1. **RETRIEVE** - Fetch relevant patterns via HNSW2. **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 |--## π Performance Optimization Protocol--### Automatic Performance Tracking-\`\`\`bash-# After any significant operation, track metrics-Bash("npx @claude-flow/cli@latest hooks post-command --command '[operation]' --track-metrics true")--# Periodically run benchmarks (every major feature)-Bash("npx @claude-flow/cli@latest performance benchmark --suite all")--# Analyze bottlenecks when performance degrades-Bash("npx @claude-flow/cli@latest performance profile --target '[component]'")-\`\`\`--### Session Persistence (Cross-Conversation Learning)-\`\`\`bash-# At session start - restore previous context-Bash("npx @claude-flow/cli@latest session restore --latest")--# At session end - persist learned patterns-Bash("npx @claude-flow/cli@latest hooks session-end --generate-summary true --persist-state true --export-metrics true")-\`\`\`--### Neural Pattern Training-\`\`\`bash-# Train on successful code patterns-Bash("npx @claude-flow/cli@latest neural train --pattern-type coordination --epochs 10")--# Predict optimal approach for new tasks-Bash("npx @claude-flow/cli@latest neural predict --input '[task description]'")--# View learned patterns-Bash("npx @claude-flow/cli@latest neural patterns --list")-\`\`\`+4. **CONSOLIDATE** - Prevent catastrophic forgetting via EWC++`;+}-## π§ Environment Variables+function envVars(): string {+ return `## Environment Variables\`\`\`bash-# ConfigurationCLAUDE_FLOW_CONFIG=./claude-flow.config.jsonCLAUDE_FLOW_LOG_LEVEL=info--# Provider API KeysANTHROPIC_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--# MemoryCLAUDE_FLOW_MEMORY_BACKEND=hybridCLAUDE_FLOW_MEMORY_PATH=./data/memory-\`\`\`--## π Doctor Health Checks--Run \`npx @claude-flow/cli@latest 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+\`\`\``;+}-## π Quick Setup+function quickSetup(): string {+ return `## Quick Setup\`\`\`bash-# Add MCP servers (auto-detects MCP mode when stdin is piped)claude mcp add claude-flow -- npx -y @claude-flow/cli@latest-claude mcp add ruv-swarm -- npx -y ruv-swarm mcp start # Optional-claude mcp add flow-nexus -- npx -y flow-nexus@latest mcp start # Optional--# Start daemonnpx @claude-flow/cli@latest daemon start--# Run doctornpx @claude-flow/cli@latest doctor --fix-\`\`\`--## π― Claude Code vs CLI 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--### CLI Tools Handle Coordination (via Bash):-- **Swarm init**: \`npx @claude-flow/cli@latest swarm init --topology <type>\`-- **Swarm status**: \`npx @claude-flow/cli@latest swarm status\`-- **Agent spawn**: \`npx @claude-flow/cli@latest agent spawn -t <type> --name <name>\`-- **Memory store**: \`npx @claude-flow/cli@latest memory store --key "mykey" --value "myvalue" --namespace patterns\`-- **Memory search**: \`npx @claude-flow/cli@latest memory search --query "search terms"\`-- **Memory list**: \`npx @claude-flow/cli@latest memory list --namespace patterns\`-- **Memory retrieve**: \`npx @claude-flow/cli@latest memory retrieve --key "mykey" --namespace patterns\`-- **Hooks**: \`npx @claude-flow/cli@latest hooks <hook-name> [options]\`--## π Memory Commands Reference (IMPORTANT)--### Store Data (ALL options shown)-\`\`\`bash-# REQUIRED: --key and --value-# OPTIONAL: --namespace (default: "default"), --ttl, --tags-npx @claude-flow/cli@latest memory store --key "pattern-auth" --value "JWT with refresh tokens" --namespace patterns-npx @claude-flow/cli@latest memory store --key "bug-fix-123" --value "Fixed null check" --namespace solutions --tags "bugfix,auth"-\`\`\`--### Search Data (semantic vector search)-\`\`\`bash-# REQUIRED: --query (full flag, not -q)-# OPTIONAL: --namespace, --limit, --threshold-npx @claude-flow/cli@latest memory search --query "authentication patterns"-npx @claude-flow/cli@latest memory search --query "error handling" --namespace patterns --limit 5-\`\`\`--### List Entries-\`\`\`bash-# OPTIONAL: --namespace, --limit-npx @claude-flow/cli@latest memory list-npx @claude-flow/cli@latest memory list --namespace patterns --limit 10-\`\`\`--### Retrieve Specific Entry-\`\`\`bash-# REQUIRED: --key-# OPTIONAL: --namespace (default: "default")-npx @claude-flow/cli@latest memory retrieve --key "pattern-auth"-npx @claude-flow/cli@latest memory retrieve --key "pattern-auth" --namespace patterns-\`\`\`--### Initialize Memory Database-\`\`\`bash-npx @claude-flow/cli@latest memory init --force --verbose-\`\`\`--**KEY**: CLI coordinates the strategy via Bash, Claude Code's Task tool executes with real agents.--## π Full Capabilities Reference--For a comprehensive overview of all Claude Flow V3 features, agents, commands, and integrations, see:+\`\`\``;+}-**\`.claude-flow/CAPABILITIES.md\`** - Complete reference generated during init+function executionBoundary(): string {+ return `## Claude Code vs CLI Tools-This includes:-- All 60+ agent types with routing recommendations-- All 26 CLI commands with 140+ subcommands-- All 27 hooks + 12 background workers-- RuVector intelligence system details-- Hive-Mind consensus mechanisms-- Integration ecosystem (agentic-flow, agentdb, ruv-swarm, flow-nexus, agentic-jujutsu)-- Performance targets and status+- Claude Code's Task tool handles ALL execution: agents, file ops, code generation, git+- CLI tools handle coordination via Bash: swarm init, memory, hooks, routing+- NEVER use CLI tools as a substitute for Task tool agents`;+}-## Support+function footer(): string {+ return `## Support- Documentation: https://github.com/ruvnet/claude-flow- Issues: https://github.com/ruvnet/claude-flow/issues-----Remember: **Claude Flow CLI coordinates, Claude Code Task tool creates!**--# important-instruction-reminders-Do what has been asked; nothing more, nothing less.-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.--## π¨ SWARM EXECUTION RULES (CRITICAL)-1. **SPAWN IN BACKGROUND**: Use \`run_in_background: true\` for all agent Task calls-2. **SPAWN ALL AT ONCE**: Put ALL agent Task calls in ONE message for parallel execution-3. **TELL USER**: After spawning, list what each agent is doing (use emojis for clarity)-4. **STOP AND WAIT**: After spawning, STOP - do NOT add more tool calls or check status-5. **NO POLLING**: Never poll TaskOutput or check swarm status - trust agents to return-6. **SYNTHESIZE**: When agent results arrive, review ALL results before proceeding-7. **NO CONFIRMATION**: Don't ask "should I check?" - just wait for results--Example spawn message:-\`\`\`-"I've launched 4 agents in background:-- π Researcher: [task]-- π» Coder: [task]-- π§ͺ Tester: [task]-- π Reviewer: [task]-Working in parallel - I'll synthesize when they complete."-\`\`\`-`;+Remember: **Claude Flow CLI coordinates, Claude Code Task tool creates!**`;}+// --- Template Composers ---+/**- * Generate minimal CLAUDE.md content+ * Template section map β defines which sections are included per template.*/-export function generateMinimalClaudeMd(options: InitOptions): string {- return `# Claude Code Configuration - Claude Flow V3--## Anti-Drift Config (PREFERRED)-\`\`\`bash-# Small teams (6-8 agents)-npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized--# Large teams (10-15 agents)-npx @claude-flow/cli@latest swarm init --topology hierarchical-mesh --max-agents 15 --strategy specialized-\`\`\`-**Valid topologies:** hierarchical, hierarchical-mesh, mesh, ring, star, hybrid--## Quick Reference--- **Topology**: hierarchical (prevents drift)-- **Max Agents**: 8-- **Strategy**: specialized-- **Memory**: ${options.runtime.memoryBackend}-- **HNSW**: ${options.runtime.enableHNSW ? 'Enabled' : 'Disabled'}--## Key Rules--1. **Batch Operations**: All related ops in ONE message-2. **Task Tool**: Claude Code's Task tool for execution-3. **CLI Tools**: Bash for coordination-4. **Anti-Drift**: Always use hierarchical + specialized for coding--## Agent Execution Pattern+const TEMPLATE_SECTIONS: Record<ClaudeMdTemplate, Array<(opts: InitOptions) => string>> = {+ minimal: [+ behavioralRules,+ fileOrganization,+ concurrencyRules,+ (_opts) => antiDriftConfig(),+ executionRules,+ (_opts) => cliCommandsTable(),+ (_opts) => quickSetup(),+ (_opts) => executionBoundary(),+ (_opts) => footer(),+ ],+ standard: [+ behavioralRules,+ fileOrganization,+ projectArchitecture,+ concurrencyRules,+ (_opts) => swarmOrchestration(),+ (_opts) => antiDriftConfig(),+ executionRules,+ (_opts) => cliCommandsTable(),+ (_opts) => agentTypes(),+ (_opts) => memoryCommands(),+ (_opts) => quickSetup(),+ (_opts) => executionBoundary(),+ (_opts) => footer(),+ ],+ full: [+ behavioralRules,+ fileOrganization,+ projectArchitecture,+ concurrencyRules,+ (_opts) => swarmOrchestration(),+ (_opts) => antiDriftConfig(),+ (_opts) => autoStartProtocol(),+ executionRules,+ (_opts) => cliCommandsTable(),+ (_opts) => agentTypes(),+ (_opts) => hooksSystem(),+ (_opts) => learningProtocol(),+ (_opts) => memoryCommands(),+ (_opts) => intelligenceSystem(),+ (_opts) => envVars(),+ (_opts) => quickSetup(),+ (_opts) => executionBoundary(),+ (_opts) => footer(),+ ],+ security: [+ behavioralRules,+ fileOrganization,+ projectArchitecture,+ concurrencyRules,+ (_opts) => swarmOrchestration(),+ (_opts) => antiDriftConfig(),+ executionRules,+ (_opts) => securitySection(),+ (_opts) => cliCommandsTable(),+ (_opts) => agentTypes(),+ (_opts) => memoryCommands(),+ (_opts) => quickSetup(),+ (_opts) => executionBoundary(),+ (_opts) => footer(),+ ],+ performance: [+ behavioralRules,+ fileOrganization,+ projectArchitecture,+ concurrencyRules,+ (_opts) => swarmOrchestration(),+ (_opts) => antiDriftConfig(),+ executionRules,+ (_opts) => performanceSection(),+ (_opts) => cliCommandsTable(),+ (_opts) => agentTypes(),+ (_opts) => memoryCommands(),+ (_opts) => intelligenceSystem(),+ (_opts) => quickSetup(),+ (_opts) => executionBoundary(),+ (_opts) => footer(),+ ],+ solo: [+ behavioralRules,+ fileOrganization,+ projectArchitecture,+ concurrencyRules,+ executionRules,+ (_opts) => cliCommandsTable(),+ (_opts) => memoryCommands(),+ (_opts) => quickSetup(),+ (_opts) => executionBoundary(),+ (_opts) => footer(),+ ],+};++// --- Public API ----\`\`\`javascript-// Single message with parallel agents (background)-Task({prompt: "Analyze...", subagent_type: "researcher", run_in_background: true})-Task({prompt: "Implement...", subagent_type: "coder", run_in_background: true})-Task({prompt: "Test...", subagent_type: "tester", run_in_background: true})-\`\`\`--## 26 CLI Commands--\`\`\`bash-# Core-npx @claude-flow/cli@latest init --wizard-npx @claude-flow/cli@latest agent spawn -t coder-npx @claude-flow/cli@latest swarm init --v3-mode-npx @claude-flow/cli@latest memory search --query "query"--# Advanced-npx @claude-flow/cli@latest daemon start-npx @claude-flow/cli@latest doctor --fix-npx @claude-flow/cli@latest security scan-npx @claude-flow/cli@latest performance benchmark-\`\`\`--## MCP Setup--\`\`\`bash-claude mcp add claude-flow -- npx -y @claude-flow/cli@latest-\`\`\`+/**+ * Generate CLAUDE.md content based on init options and template.+ * Template is determined by: options.runtime.claudeMdTemplate > explicit param > 'standard'+ */+export function generateClaudeMd(options: InitOptions, template?: ClaudeMdTemplate): string {+ const tmpl = template ?? options.runtime.claudeMdTemplate ?? 'standard';+ const sections = TEMPLATE_SECTIONS[tmpl] ?? TEMPLATE_SECTIONS.standard;-## π Full Reference+ const header = `# Claude Code Configuration - Claude Flow V3\n`;+ const body = sections.map(fn => fn(options)).join('\n\n');-See **\`.claude-flow/CAPABILITIES.md\`** for complete documentation of all 60+ agents, 26 commands, 27 hooks, and integrations.+ return `${header}\n${body}\n`;+}-----Remember: **Claude Flow CLI coordinates, Claude Code Task tool creates!**-`;+/**+ * Generate minimal CLAUDE.md content (backward-compatible alias).+ */+export function generateMinimalClaudeMd(options: InitOptions): string {+ return generateClaudeMd(options, 'minimal');}+/** Available template names for CLI wizard */+export const CLAUDE_MD_TEMPLATES: Array<{ name: ClaudeMdTemplate; description: string }> = [+ { name: 'minimal', description: 'Quick start β behavioral rules, anti-drift config, CLI reference (~120 lines)' },+ { name: 'standard', description: 'Recommended β swarm orchestration, agents, memory commands (~250 lines)' },+ { name: 'full', description: 'Everything β hooks, learning protocol, intelligence system (~400 lines)' },+ { name: 'security', description: 'Security-focused β adds security scanning, audit protocols, CVE checks' },+ { name: 'performance', description: 'Performance-focused β adds benchmarking, profiling, optimization protocols' },+ { name: 'solo', description: 'Solo developer β no swarm, simple agent usage, memory commands (~150 lines)' },+];+export default generateClaudeMd;