π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat: lean CLAUDE.md generator with SendMessage-first coordination
Reuvenc44f527a1ecc
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0fcf1b2fac..cd48648e42 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,8 +1,8 @@# Claude Code Configuration - Ruflo v3.5-> **Ruflo v3.5** (2026-04-07) β Stable release with verified capabilities.-> 6,000+ commits, 314 MCP tools, 16 agent roles + custom types, 19 AgentDB controllers.+> **Ruflo v3.6** (2026-04-29) β Stable release with agent federation and comms-first coordination.+> 6,000+ commits, 314 MCP tools, 16 agent roles + custom types, 19 AgentDB controllers, 21 native plugins.## Behavioral Rules (Always Enforced)@@ -254,39 +254,50 @@ const designDocs = await orchestrator.getMemory('design-decisions');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)+// STEP 1: Initialize swarm coordination via MCPmcp__ruv-swarm__swarm_init({topology: "hierarchical",maxAgents: 8,strategy: "specialized"})-// 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 2: Spawn NAMED agents concurrently β all in ONE message+// Each agent knows WHO to message next in the pipeline+Task({+ prompt: "Research requirements and codebase. SendMessage findings to 'architect' when done.",+ subagent_type: "researcher", name: "researcher", run_in_background: true+})+Task({+ prompt: "Wait for research from 'researcher'. Design implementation. SendMessage design to 'coder'.",+ subagent_type: "system-architect", name: "architect", run_in_background: true+})+Task({+ prompt: "Wait for design from 'architect'. Implement the solution. SendMessage code paths to 'tester'.",+ subagent_type: "coder", name: "coder", run_in_background: true+})+Task({+ prompt: "Wait for implementation from 'coder'. Write tests. SendMessage results to 'reviewer'.",+ subagent_type: "tester", name: "tester", run_in_background: true+})+Task({+ prompt: "Wait for test results from 'tester'. Review code quality and security. Report findings.",+ subagent_type: "reviewer", name: "reviewer", run_in_background: true+})-// STEP 3: Batch all todos+// STEP 3: Kick off the pipeline+SendMessage({ to: "researcher", summary: "Start research", message: "[task description and context]" })++// STEP 4: Batch todosTodoWrite({ 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"}+ {content: "Research and analyze requirements", status: "in_progress", activeForm: "Researching"},+ {content: "Design architecture", status: "pending", activeForm: "Designing"},+ {content: "Implement solution", status: "pending", activeForm: "Implementing"},+ {content: "Write tests", status: "pending", activeForm: "Testing"},+ {content: "Review and finalize", status: "pending", activeForm: "Reviewing"}]})-// 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()})-})+// Pipeline flow via SendMessage:+// researcher βββ architect βββ coder βββ tester βββ reviewer```### Agent Routing (Anti-Drift)@@ -530,122 +541,165 @@ const config = optimizer.getOptimalConfig(agentCount);### Testing & Validation`tdd-london-swarm`, `production-validator`-## Agent Teams (Multi-Agent Coordination)--Claude Code's experimental Agent Teams feature is fully integrated with Claude Flow for advanced multi-agent coordination.+## Agent Teams & Comms System-### Enabling Agent Teams+Agent Teams turns Claude Code into a multi-agent system where named agents communicate in real-time via `SendMessage`. The comms system is the primary coordination mechanism β agents talk to each other, not just to the lead.-Agent Teams is automatically enabled when you run `npx claude-flow@v3alpha init`. The following is added to `.claude/settings.json`:+### Architecture-```json-{- "env": {- "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"- },- "claudeFlow": {- "agentTeams": {- "enabled": true,- "teammateMode": "auto",- "taskListEnabled": true,- "mailboxEnabled": true- }- }-}+```+Team Lead (you)+ βββ SendMessage ββ architect (named agent)+ βββ SendMessage ββ developer (named agent)+ βββ SendMessage ββ tester (named agent)+ βββ SendMessage ββ reviewer (named agent)+ β agents can message each other by name```-### Agent Teams Components--| Component | Tool | Purpose |-|-----------|------|---------|-| **Team Lead** | You (main Claude) | Coordinates teammates, assigns tasks, reviews results |-| **Teammates** | `Task` tool | Sub-agents spawned to work on specific tasks |-| **Task List** | `TaskCreate/TaskList/TaskUpdate` | Shared todo list visible to all team members |-| **Mailbox** | `SendMessage` | Inter-agent messaging for coordination |+### Core Principle: Named Agents + SendMessage-### Creating and Managing Teams+Every agent MUST have a `name` so it's addressable. Communication happens via `SendMessage`, not polling or shared memory.```javascript-// Create a team-TeamCreate({- team_name: "feature-dev",- description: "Building new feature",- agent_type: "coordinator"-})--// Create shared tasks-TaskCreate({ subject: "Design API", description: "...", activeForm: "Designing" })-TaskCreate({ subject: "Implement endpoints", description: "...", activeForm: "Implementing" })-TaskCreate({ subject: "Write tests", description: "...", activeForm: "Testing" })--// Spawn teammates (run in background for parallel work)+// STEP 1: Spawn named agents (all in ONE message, background)Task({- prompt: "Design the API according to task #1...",+ prompt: "Design the API. When done, send your design to 'developer' via SendMessage.",subagent_type: "system-architect",- team_name: "feature-dev",name: "architect",run_in_background: true})Task({- prompt: "Implement endpoints from task #2...",+ prompt: "Wait for architect's design via SendMessage. Then implement it. Send code to 'tester'.",subagent_type: "coder",- team_name: "feature-dev",name: "developer",run_in_background: true})+Task({+ prompt: "Wait for developer's code via SendMessage. Write tests. Send results to 'reviewer'.",+ subagent_type: "tester",+ name: "tester",+ run_in_background: true+})++// STEP 2: Kick off the pipeline by messaging the first agent+SendMessage({+ to: "architect",+ summary: "Start API design",+ message: "Design a REST API for user management with CRUD endpoints. Send the design to 'developer' when done."+})```-### Agent Teams Hooks+### SendMessage Protocol-| Hook | Trigger | Purpose |-|------|---------|---------|-| `TeammateIdle` | Teammate finishes turn | Auto-assign pending tasks to idle teammates |-| `TaskCompleted` | Task marked complete | Train patterns from successful work, notify lead |+```javascript+// Lead β Teammate: assign work+SendMessage({ to: "developer", summary: "Implement auth", message: "Build OAuth2 flow..." })-### Hook Commands+// Lead β Teammate: redirect priorities+SendMessage({ to: "developer", summary: "Prioritize auth", message: "Auth endpoint is blocking tester, do it first." })-```bash-# Handle idle teammate (auto-assigns available tasks)-npx claude-flow@v3alpha hooks teammate-idle --auto-assign true+// Lead β Teammate: provide context from another agent's results+SendMessage({ to: "tester", summary: "Architect output", message: "The architect designed these endpoints: [details]. Write tests for them." })-# Handle task completion (trains patterns, notifies lead)-npx claude-flow@v3alpha hooks task-completed -i task-123 --train-patterns true+// Lead β Teammate: graceful shutdown+SendMessage({ to: "developer", message: { type: "shutdown_request" } })+```-# Check on team progress-TaskList+### Coordination Patterns-# Send message to teammate-SendMessage({- type: "message",- recipient: "developer",- content: "Please prioritize the auth endpoint",- summary: "Prioritize auth"+**Pipeline (A β B β C)** β each agent messages the next when done:+```+architect ββSendMessageβββ developer ββSendMessageβββ tester ββSendMessageβββ reviewer+```+Tell each agent WHO to message next in their prompt.++**Fan-out / Fan-in** β lead spawns parallel agents, collects results:+```+ ββ researcher-1 ββββ+lead βββββΌβ researcher-2 βββββββ lead synthesizes+ ββ researcher-3 ββββ+```+Spawn with `run_in_background: true`. Results arrive as task completions.++**Supervisor / Worker** β lead assigns, workers report back:+```+lead βββSendMessageβββ worker-1+lead βββSendMessageβββ worker-2+lead βββSendMessageβββ worker-3+```+Lead sends tasks via SendMessage, workers respond with results.++### Agent Prompt Template (Comms-Aware)++When spawning agents that need to coordinate, include comms instructions:++```javascript+Task({+ prompt: `You are the architect for this feature team.++YOUR TASK: Design the database schema for user management.++COMMS PROTOCOL:+- When your design is ready, send it to "developer" via SendMessage+- If you need clarification, message the team lead (just output text)+- Include file paths and key decisions in your message++DELIVERABLE: Schema design with entity relationships, indexes, and migration plan.`,+ subagent_type: "system-architect",+ name: "architect",+ run_in_background: true})+```-# Shutdown teammate gracefully-SendMessage({- type: "shutdown_request",- recipient: "developer",- content: "Work complete, shutting down"+### Full Team Spawn Example++```javascript+// Create shared task list first+TaskCreate({ subject: "Design schema", description: "...", activeForm: "Designing" })+TaskCreate({ subject: "Implement models", description: "...", activeForm: "Implementing" })+TaskCreate({ subject: "Write tests", description: "...", activeForm: "Testing" })+TaskCreate({ subject: "Security review", description: "...", activeForm: "Reviewing" })++// Spawn ALL named agents in ONE message+Task({+ prompt: "Design the schema. SendMessage to 'developer' with your design when done. Update task #1.",+ subagent_type: "system-architect", name: "architect", run_in_background: true+})+Task({+ prompt: "Wait for schema from 'architect'. Implement models + endpoints. SendMessage to 'tester'. Update task #2.",+ subagent_type: "coder", name: "developer", run_in_background: true+})+Task({+ prompt: "Wait for code from 'developer'. Write integration tests. SendMessage results to 'security'. Update task #3.",+ subagent_type: "tester", name: "tester", run_in_background: true+})+Task({+ prompt: "Wait for test results from 'tester'. Review for vulnerabilities. Update task #4.",+ subagent_type: "security-auditor", name: "security", run_in_background: true})```-### Best Practices for Agent Teams+### Agent Teams Hooks-1. **Spawn teammates in background**: Use `run_in_background: true` for parallel work-2. **Create tasks first**: Use TaskCreate before spawning teammates so they have work-3. **Use descriptive names**: Name teammates by role (architect, developer, tester)-4. **Don't poll status**: Wait for teammates to message back or complete-5. **Graceful shutdown**: Always send shutdown_request before TeamDelete-6. **Clean up**: Use TeamDelete after all teammates have shut down+| Hook | Trigger | Purpose |+|------|---------|---------|+| `TeammateIdle` | Teammate finishes turn | Auto-assign pending tasks via SendMessage |+| `TaskCompleted` | Task marked complete | Train patterns, notify lead via SendMessage |-### Teammate Display Modes+```bash+npx claude-flow@v3alpha hooks teammate-idle --auto-assign true+npx claude-flow@v3alpha hooks task-completed -i task-123 --train-patterns true+```-| Mode | Description |-|------|-------------|-| `auto` | Automatically selects best mode for environment |-| `in-process` | Teammates run in same process (default for CI/background) |-| `tmux` | Split-pane display in terminal (requires tmux) |+### Rules++1. **Always name agents** β use `name: "role-name"` so they're addressable+2. **Comms over memory** β use SendMessage for real-time coordination, memory for persistence+3. **Pipeline prompts** β tell each agent WHO to message next and WHAT to send+4. **Spawn all at once** β all Task calls in ONE message with `run_in_background: true`+5. **Don't poll** β agents message back when done; wait for task completion notifications+6. **Graceful shutdown** β send `{ type: "shutdown_request" }` before TeamDelete+7. **Lead synthesizes** β when agents complete, review ALL results before responding to user## V3 Hooks System (17 Hooks + 12 Workers)diff --git a/package-lock.json b/package-lock.jsonindex dfca2fd914..0f0b4d8cd3 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "claude-flow",- "version": "3.6.9",+ "version": "3.6.10","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "claude-flow",- "version": "3.6.9",+ "version": "3.6.10","license": "MIT","dependencies": {"semver": "^7.6.0",diff --git a/package.json b/package.jsonindex 3caeeb5cc3..4b5c8056af 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "claude-flow",- "version": "3.6.9",+ "version": "3.6.10","description": "Ruflo - Enterprise AI agent orchestration for Claude Code. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration","main": "dist/index.js","type": "module",diff --git a/ruflo/package.json b/ruflo/package.jsonindex 6a705f300e..b770329c24 100644--- a/ruflo/package.json+++ b/ruflo/package.json@@ -1,6 +1,6 @@{"name": "ruflo",- "version": "3.6.9",+ "version": "3.6.10","description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration","main": "bin/ruflo.js","type": "module",diff --git a/v3/@claude-flow/cli/README.md b/v3/@claude-flow/cli/README.mdindex 2071521ffd..ac1c09218b 100644--- a/v3/@claude-flow/cli/README.md+++ b/v3/@claude-flow/cli/README.md@@ -12,15 +12,15 @@</div>-Deploy 16 specialized agent roles + custom types in coordinated swarms with self-learning capabilities, fault-tolerant consensus, and enterprise-grade security.+Orchestrate 100+ specialized AI agents across machines, teams, and trust boundaries. Ruflo adds coordinated swarms, self-learning memory, federated comms, and enterprise security to Claude Code β so agents don't just run, they collaborate.### Why Ruflo?-> **Why Ruflo?** Claude Flow is now Ruflo β named by Ruv, who loves Rust, flow states, and building things that feel inevitable. The "Ru" is the Ruv. The "flo" is the flow. Underneath, WASM kernels written in Rust power the policy engine, embeddings, and proof system.+> Claude Flow is now Ruflo β named by Ruv, who loves Rust, flow states, and building things that feel inevitable. The "Ru" is the Ruv. The "flo" is the flow. Underneath, WASM kernels written in Rust power the policy engine, embeddings, and proof system.-### Getting into the Flow+### What Ruflo Does-Ruflo is a comprehensive AI agent orchestration framework that transforms Claude Code into a powerful multi-agent development platform. It enables teams to deploy, coordinate, and optimize specialized AI agents working together on complex software engineering tasks.+One `init` gives Claude Code a nervous system: agents self-organize into swarms, learn from every task, remember across sessions, and β with federation β securely talk to agents on other machines without leaking data. You keep writing code. Ruflo handles the coordination.```Self-Learning / Self-Optimizing Agent Architecture@@ -48,10 +48,11 @@ Install Ruflo as a native Claude Code plugin -- adds skills, commands, agents, a/plugin install ruflo-core@ruflo/plugin install ruflo-swarm@ruflo/plugin install ruflo-autopilot@ruflo+/plugin install ruflo-federation@ruflo```<details>-<summary><strong>All 20 plugins</strong></summary>+<summary><strong>All 21 plugins</strong></summary>| Plugin | What it adds ||--------|-------------|@@ -74,6 +75,7 @@ Install Ruflo as a native Claude Code plugin -- adds skills, commands, agents, a| **ruflo-testgen** | Test gap detection, TDD workflow, tester agent || **ruflo-docs** | Doc generation, drift detection, docs-writer agent || **ruflo-plugin-creator** | Scaffold, validate, and publish new plugins |+| **ruflo-federation** | Zero-trust agent federation, PII pipeline, cross-installation comms || **ruflo-goals** | GOAP planning, deep research, long-horizon tracking |</details>@@ -105,13 +107,80 @@ claude mcp add ruflo -- npx -y @claude-flow/cli@latest| Capability | Description ||------------|-------------|| π€ **100+ Agents** | Specialized agents for coding, testing, security, docs, architecture |+| π‘ **Comms Layer** | Zero-trust federation β agents across machines/orgs discover, authenticate, and exchange work securely || π **Swarm Coordination** | Hierarchical, mesh, and adaptive topologies with consensus || π§ **Self-Learning** | SONA neural patterns, ReasoningBank, trajectory learning || πΎ **Vector Memory** | HNSW-indexed AgentDB with 150x-12,500x faster search || β‘ **Background Workers** | 12 auto-triggered workers (audit, optimize, testgaps, etc.) |-| π§© **Plugin Marketplace** | 20 native Claude Code plugins + 20 npm plugins |+| π§© **Plugin Marketplace** | 21 native Claude Code plugins + 21 npm plugins || π **Multi-Provider** | Claude, GPT, Gemini, Cohere, Ollama with smart routing || π‘οΈ **Security** | AIDefence, input validation, CVE remediation, path traversal prevention |+| π **Agent Federation** | Cross-installation agent collaboration with zero-trust security++### Agent Federation β Slack for Agents++```+Your Agent --> [ Remove secrets ] --> [ Sign message ] --> [ Encrypted channel ]+ Emails, SSNs, Proves it came No one reads it+ keys stripped from you in transit+ |+ v+Their Agent <-- [ Block attacks ] <-- [ Check identity ] <------++ Stops prompt Rejects forgeries+ injection++ Audit trail on both sides.+ Trust builds over time. Bad behavior = instant downgrade.+```++Slack gave teams channels. Federation gives agents the same thing β **shared workspaces across trust boundaries**, where agents on different machines, orgs, or cloud regions can discover each other, prove who they are, and collaborate on tasks.++The difference: some channels are trusted, some aren't. [`@claude-flow/plugin-agent-federation`](https://github.com/ruvnet/ruflo/issues/1669) handles that automatically. Your agents join a federation, get verified via mTLS + ed25519, and start exchanging work β with PII stripped before anything leaves your node and every message auditable. Untrusted agents can still participate at lower privilege: they see discovery info, not your memory. As they prove reliable, trust upgrades. If they misbehave, they get downgraded instantly β no human in the loop required.++You don't configure handshakes or manage certificates. You `federation init`, `federation join`, and your agents start talking. The protocol handles identity, the PII pipeline handles data safety, and the audit trail handles compliance.++<details>+<summary><strong>Federation capabilities</strong></summary>++| | Capability | How it works |+|---|---|---|+| π | **Zero-trust federation** | Remote agents start untrusted. Identity proven via mTLS + ed25519 challenge-response. No API keys, no shared secrets. |+| π‘οΈ | **PII-gated data flow** | 14-type detection pipeline scans every outbound message. Per-trust-level policies: BLOCK, REDACT, HASH, or PASS. Adaptive calibration reduces false positives. |+| π | **Behavioral trust scoring** | Formula (`0.4Γsuccess + 0.2Γuptime + 0.2Γthreat + 0.2Γintegrity`) continuously evaluates peers. Upgrades require history; downgrades are instant. |+| π | **Compliance built-in** | HIPAA, SOC2, GDPR audit trails as compliance modes. Every federation event produces a structured record searchable via HNSW. |+| π€ | **9 MCP tools + 10 CLI commands** | Full lifecycle: `federation_init`, `federation_send`, `federation_trust`, `federation_audit`, and more. |++</details>++<details>+<summary><strong>Example: two teams sharing fraud signals without sharing customer data</strong></summary>++```bash+# Team A: initialize federation and generate keypair+npx claude-flow@latest federation init++# Team A: join Team B's federation endpoint+npx claude-flow@latest federation join wss://team-b.example.com:8443++# Team A: send a task β PII is stripped automatically before it leaves+npx claude-flow@latest federation send --to team-b --type task-request \+ --message "Analyze transaction patterns for account anomalies"++# Team A: check peer trust levels and session health+npx claude-flow@latest federation status+```++</details>++See [issue #1669](https://github.com/ruvnet/ruflo/issues/1669) for the complete architecture, trust model, and implementation roadmap.++```bash+# Claude Code plugin+/plugin install ruflo-federation@ruflo++# Or via CLI+npx claude-flow@latest plugins install @claude-flow/plugin-agent-federation+```<details><summary><strong>Claude Code: With vs Without Ruflo</strong></summary>diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.jsonindex 42da0acce3..e65f0bfd30 100644--- a/v3/@claude-flow/cli/package.json+++ b/v3/@claude-flow/cli/package.json@@ -1,6 +1,6 @@{"name": "@claude-flow/cli",- "version": "3.6.9",+ "version": "3.6.10","type": "module","description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code","main": "dist/src/index.js",diff --git a/v3/@claude-flow/cli/src/init/claudemd-generator.ts b/v3/@claude-flow/cli/src/init/claudemd-generator.tsindex 4315609c89..56f7acc2f3 100644--- a/v3/@claude-flow/cli/src/init/claudemd-generator.ts+++ b/v3/@claude-flow/cli/src/init/claudemd-generator.ts@@ -1,577 +1,388 @@/*** CLAUDE.md Generator- * Generates enforceable, analyzer-optimized Claude Code configuration- * with template variants for different usage patterns.+ * Generates lean, enforceable Claude Code configuration optimized for token efficiency.** Templates: minimal | standard | full | security | performance | solo- * All templates use bullet-format rules with imperative keywords for enforceability.+ * All templates use imperative rules and agent comms-first coordination.*/import type { InitOptions, ClaudeMdTemplate } from './types.js';-// --- Section Generators (each returns enforceable markdown) ---+// --- Section Generators ---function behavioralRules(): string {- return `## Behavioral Rules (Always Enforced)+ return `## Rules- 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+- NEVER create files unless absolutely necessary β prefer editing existing files+- NEVER create documentation files unless explicitly requested+- NEVER save working files or tests to root β use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\`- ALWAYS read a file before editing it-- NEVER commit secrets, credentials, or .env files`;-}--function fileOrganization(): string {- return `## File Organization--- 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`;-}--function projectArchitecture(options: InitOptions): string {- return `## Project Architecture--- Follow Domain-Driven Design with bounded contexts+- NEVER commit secrets, credentials, or .env files- 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+- Validate input at system boundaries`;+}-### Project Config+function agentComms(): string {+ return `## Agent Comms (SendMessage-First Coordination)-- **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'}`;-}+Named agents coordinate via \`SendMessage\`, not polling or shared state.-function concurrencyRules(): string {- return `## Concurrency: 1 MESSAGE = ALL RELATED OPERATIONS+\`\`\`+Lead (you) ββ architect ββ developer ββ tester ββ reviewer+ (named agents message each other directly)+\`\`\`-- All operations MUST be concurrent/parallel in a single message-- Use Claude Code's Agent tool for spawning agents, not just MCP-- ALWAYS spawn ALL agents in ONE message with full instructions via Agent tool-- ALWAYS batch ALL file reads/writes/edits in ONE message-- ALWAYS batch ALL Bash commands in ONE message`;-}+### Spawning a Coordinated Team-function swarmOrchestration(): string {- return `## Swarm Orchestration+\`\`\`javascript+// ALL agents in ONE message, each knows WHO to message next+Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.",+ subagent_type: "researcher", name: "researcher", run_in_background: true })+Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.",+ subagent_type: "system-architect", name: "architect", run_in_background: true })+Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.",+ subagent_type: "coder", name: "coder", run_in_background: true })+Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.",+ subagent_type: "tester", name: "tester", run_in_background: true })+Agent({ prompt: "Wait for 'tester'. Review code quality and security.",+ subagent_type: "reviewer", name: "reviewer", run_in_background: true })++// Kick off the pipeline+SendMessage({ to: "researcher", summary: "Start", message: "[task context]" })+\`\`\`-- MUST initialize the swarm using CLI tools when starting complex tasks-- MUST spawn concurrent agents using Claude Code's Agent tool-- Never use CLI tools alone for execution β Agent tool agents do the actual work-- MUST call CLI tools AND Agent tool in ONE message for complex work+### Patterns-### 3-Tier Model Routing (ADR-026)+| Pattern | Flow | Use When |+|---------|------|----------|+| **Pipeline** | A β B β C β D | Sequential dependencies (feature dev) |+| **Fan-out** | Lead β A, B, C β Lead | Independent parallel work (research) |+| **Supervisor** | Lead β workers | Ongoing coordination (complex refactor) |-| 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%) |+### Rules-- For Tier 1 simple transforms, use Edit tool directly β no LLM agent needed`;+- ALWAYS name agents β \`name: "role"\` makes them addressable+- ALWAYS include comms instructions in prompts β who to message, what to send+- Spawn ALL agents in ONE message with \`run_in_background: true\`+- After spawning: STOP, tell user what's running, wait for results+- NEVER poll status β agents message back or complete automatically`;}-function antiDriftConfig(): string {- return `## Swarm Configuration & Anti-Drift+function swarmConfig(options: InitOptions): string {+ return `## Swarm & Routing-- 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+### Config+- **Topology**: ${options.runtime.topology} (anti-drift)+- **Max Agents**: ${options.runtime.maxAgents}+- **Memory**: ${options.runtime.memoryBackend}+- **HNSW**: ${options.runtime.enableHNSW ? 'Enabled' : 'Disabled'}+- **Neural**: ${options.runtime.enableNeural ? 'Enabled' : 'Disabled'}\`\`\`bashnpx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized-\`\`\``;-}--function autoStartProtocol(): string {- return `## Swarm Protocols & Routing--### Auto-Start Swarm Protocol--When the user requests a complex task, spawn agents in background and WAIT:--\`\`\`javascript-// STEP 1: Initialize swarm coordination-Bash("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-Agent("Research requirements", "Analyze codebase patterns and store findings in memory", {subagent_type: "researcher", run_in_background: true})-Agent("Design architecture", "Design architecture based on research", {subagent_type: "system-architect", run_in_background: true})-Agent("Implement solution", "Implement the solution following the design", {subagent_type: "coder", run_in_background: true})-Agent("Write tests", "Write comprehensive tests for the implementation", {subagent_type: "tester", run_in_background: true})-Agent("Review code quality", "Review code quality, security, and best practices", {subagent_type: "reviewer", run_in_background: true})\`\`\`### Agent Routing-| Code | Task | Agents |-|------|------|--------|-| 1 | Bug Fix | coordinator, researcher, coder, tester |-| 3 | Feature | coordinator, architect, coder, tester, reviewer |-| 5 | Refactor | coordinator, architect, coder, reviewer |-| 7 | Performance | coordinator, perf-engineer, coder |-| 9 | Security | coordinator, security-architect, auditor |--### Task Complexity Detection--- 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`;+| Task | Agents | Topology |+|------|--------|----------|+| Bug Fix | researcher, coder, tester | hierarchical |+| Feature | architect, coder, tester, reviewer | hierarchical |+| Refactor | architect, coder, reviewer | hierarchical |+| Performance | perf-engineer, coder | hierarchical |+| Security | security-architect, auditor | hierarchical |++### When to Swarm+- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance+- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions++### 3-Tier Model Routing++| Tier | Handler | Use Cases |+|------|---------|-----------|+| 1 | Agent Booster (WASM) | Simple transforms β skip LLM, use Edit directly |+| 2 | Haiku | Simple tasks, low complexity |+| 3 | Sonnet/Opus | Architecture, security, complex reasoning |`;}-function executionRules(): string {- return `## Swarm Execution Rules+function memoryAndLearning(): string {+ return `## Memory & Learning-- ALWAYS use \`run_in_background: true\` for all Agent tool calls-- ALWAYS put ALL Agent calls in ONE message for parallel execution-- After spawning, STOP β do NOT add more tool calls or check status-- Never poll agent status repeatedly β trust agents to return-- When agent results arrive, review ALL results before proceeding`;-}+### Before 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]"+\`\`\`++### After Success+\`\`\`bash+npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]"+npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true+\`\`\`-function cliCommandsTable(): string {- return `## V3 CLI Commands+### MCP Tools (use \`ToolSearch("keyword")\` to discover)-### Core Commands+| Category | Key Tools |+|----------|-----------|+| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` |+| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` |+| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` |+| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` |+| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` |+| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` |+| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` |-| Command | Subcommands | Description |-|---------|-------------|-------------|-| \`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 |+### Background Workers-### Quick CLI Examples+| Worker | When |+|--------|------|+| \`audit\` | After security changes |+| \`optimize\` | After performance work |+| \`testgaps\` | After adding features |+| \`map\` | Every 5+ file changes |+| \`document\` | After API changes |\`\`\`bash-npx @claude-flow/cli@latest init --wizard-npx @claude-flow/cli@latest agent spawn -t coder --name my-coder-npx @claude-flow/cli@latest swarm init --v3-mode-npx @claude-flow/cli@latest memory search --query "authentication patterns"-npx @claude-flow/cli@latest doctor --fix+npx @claude-flow/cli@latest hooks worker dispatch --trigger audit\`\`\``;}function agentTypes(): string {- return `## Available Agents (16 Roles + Custom)--### Core Development-\`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\`+ return `## Agents-### Specialized-\`security-architect\`, \`security-auditor\`, \`memory-specialist\`, \`performance-engineer\`+**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\`+**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\`+**Security**: \`security-architect\`, \`security-auditor\`+**Performance**: \`performance-engineer\`, \`perf-analyzer\`+**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\`+**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\`-### Coordination-\`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\`--### GitHub & Repository-\`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\`--Any string can be used as a custom agent type β these are the typed roles with specialized behavior.`;+Any string works as a custom agent type.`;}-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 |-|--------|----------|-------------|-| \`optimize\` | high | Performance optimization |-| \`audit\` | critical | Security analysis |-| \`testgaps\` | normal | Test coverage analysis |-| \`map\` | normal | Codebase mapping |-| \`deepdive\` | normal | Deep code analysis |-| \`document\` | normal | Auto-documentation |+function cliQuickRef(): string {+ return `## CLI Quick Reference\`\`\`bash-npx @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 worker dispatch --trigger audit-\`\`\``;-}--function learningProtocol(): string {- return `## Auto-Learning Protocol--### 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]"+npx @claude-flow/cli@latest init --wizard # Setup+npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm+npx @claude-flow/cli@latest memory search --query "" # Vector search+npx @claude-flow/cli@latest hooks route --task "" # Route to agent+npx @claude-flow/cli@latest doctor --fix # Diagnostics+npx @claude-flow/cli@latest security scan # Security scan+npx @claude-flow/cli@latest performance benchmark # Benchmarks\`\`\`-### 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-\`\`\`--- ALWAYS check memory before starting new features, debugging, or refactoring-- ALWAYS store patterns in memory after solving bugs, completing features, or finding optimizations`;+26 commands, 140+ subcommands. Use \`--help\` on any command for details.`;}-function memoryCommands(): string {- return `## Memory & Vector Search--### MCP Tools (use via ToolSearch to discover)--| Tool | Description |-|------|-------------|-| \`memory_store\` | Store value with ONNX 384-dim vector embedding |-| \`memory_search\` | Semantic vector search by query |-| \`memory_retrieve\` | Get entry by key |-| \`memory_list\` | List entries in namespace |-| \`memory_delete\` | Delete entry |-| \`memory_import_claude\` | Import Claude Code memories into AgentDB (allProjects=true for all) |-| \`memory_search_unified\` | Search across ALL namespaces (Claude + AgentDB + patterns) |-| \`memory_bridge_status\` | Show bridge health, vectors, SONA, intelligence |--### CLI Commands+function setupAndBoundary(): string {+ return `## Setup\`\`\`bash-# Store with vector embedding-npx @claude-flow/cli@latest memory store --key "pattern-auth" --value "JWT with refresh" --namespace patterns--# Semantic search-npx @claude-flow/cli@latest memory search --query "authentication patterns"--# Import all Claude Code memories into AgentDB-node .claude/helpers/auto-memory-hook.mjs import-all+claude mcp add claude-flow -- npx -y @claude-flow/cli@latest+npx @claude-flow/cli@latest daemon start+npx @claude-flow/cli@latest doctor --fix\`\`\`-### Claude Code β AgentDB Bridge--Claude Code auto-memory files (\`~/.claude/projects/*/memory/*.md\`) are automatically imported into AgentDB with ONNX vector embeddings on session start. Use \`memory_search_unified\` to search across both stores.`;-}--function securityRulesLight(): string {- return `## Security Rules--- NEVER hardcode API keys, secrets, or credentials in source files-- NEVER commit .env files or any file containing secrets-- Always validate user input at system boundaries-- Always sanitize file paths to prevent directory traversal-- Run \`npx @claude-flow/cli@latest security scan\` after security-related changes`;+**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash.`;}function buildAndTest(): string {return `## Build & Test-\`\`\`bash-# Build-npm run build--# Test-npm test+- ALWAYS run tests after code changes+- ALWAYS verify build succeeds before committing-# Lint-npm run lint-\`\`\`--- ALWAYS run tests after making code changes-- ALWAYS verify build succeeds before committing`;+\`\`\`bash+npm run build && npm test+\`\`\``;}function securitySection(): string {- return `## Security Protocol+ return `## Security-- 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+- NEVER hardcode secrets in source β use environment variables+- Always validate input at boundaries (Zod schemas)+- Always sanitize file paths (prevent traversal)+- Always use parameterized queries (prevent injection)-### Security Scanning\`\`\`bashnpx @claude-flow/cli@latest security scan --depth fullnpx @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`;+Agents: \`security-architect\` (threat modeling), \`security-auditor\` (vulnerability detection)`;}function performanceSection(): string {- return `## Performance Optimization Protocol+ return `## Performance-- Always run benchmarks before and after performance changes-- Always profile before optimizing β never guess at bottlenecks-- Prefer algorithmic improvements over micro-optimizations-- Use DiskANN or HNSW for vector search (auto-selected by dataset size)-- Use Int8 quantization for ~4x memory reduction when needed+- Always benchmark before AND after optimization+- Always profile before optimizing β never guess bottlenecks+- Use HNSW/DiskANN for vector search, Int8 quantization for memory reduction-### Performance Tooling\`\`\`bashnpx @claude-flow/cli@latest performance benchmark --suite allnpx @claude-flow/cli@latest performance profile --target "[component]"-npx @claude-flow/cli@latest performance metrics --format table\`\`\`-### Performance Agents-- \`performance-engineer\` β profiling, benchmarking, optimization-- \`perf-analyzer\` β bottleneck detection, analysis-- Use agent routing code 7 (hierarchical/specialized) for performance tasks`;+Agents: \`performance-engineer\` (profiling), \`perf-analyzer\` (bottleneck detection)`;}-function intelligenceSystem(): string {- return `## Intelligence System--- **SONA**: Self-Optimizing Pattern Learning (sub-millisecond pattern matching)-- **HNSW/DiskANN**: HNSW-indexed vector search with DiskANN SSD-friendly fallback-- **ONNX Embeddings**: all-MiniLM-L6-v2, 384 dimensions, real neural vectors-- **ReasoningBank**: Pattern storage with file persistence--The learning pipeline:-1. **RETRIEVE** β Fetch relevant patterns via HNSW/DiskANN vector search-2. **JUDGE** β Evaluate with verdicts (success/failure) from post-task hooks-3. **DISTILL** β Extract key learnings, store as patterns with embeddings-4. **CONSOLIDATE** β Persist patterns to disk across sessions`;-}+function hooksRef(): string {+ return `## Hooks-function envVars(): string {- return `## Environment Variables+| Hook | Purpose |+|------|---------|+| \`pre-task\` / \`post-task\` | Task lifecycle + learning |+| \`pre-edit\` / \`post-edit\` | File editing + neural training |+| \`session-start\` / \`session-end\` | Session persistence |+| \`route\` | Route to optimal agent |+| \`intelligence\` | Pattern learning (SONA) |+| \`worker\` | Background worker dispatch |\`\`\`bash-CLAUDE_FLOW_CONFIG=./claude-flow.config.json-CLAUDE_FLOW_LOG_LEVEL=info-ANTHROPIC_API_KEY=sk-ant-...-CLAUDE_FLOW_MEMORY_BACKEND=hybrid-CLAUDE_FLOW_MEMORY_PATH=./data/memory+npx @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 session-start --session-id "[id]"+npx @claude-flow/cli@latest hooks route --task "[task]"+npx @claude-flow/cli@latest hooks worker dispatch --trigger audit\`\`\``;}-function mcpToolDiscovery(): string {- return `## Key MCP Tools (314 available β use ToolSearch to discover)--### Most Used Tools--| Category | Tools | What They Do |-|----------|-------|-------------|-| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | Store/search with ONNX vector embeddings |-| **Claude Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | Import Claude memories into AgentDB |-| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | Multi-agent coordination |-| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | Agent lifecycle |-| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_spawn\`, \`hive-mind_consensus\` | Byzantine/Raft consensus |-| **Hooks** | \`hooks_route\`, \`hooks_session-start\`, \`hooks_post-task\` | Task routing + learning |-| **Workers** | \`hooks_worker-list\`, \`hooks_worker-dispatch\` | 12 background workers |-| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\` | Prompt injection detection |-| **Intelligence** | \`hooks_intelligence\`, \`neural_status\` | Pattern learning + SONA |--### Swarm Capabilities--- **Topologies**: hierarchical (anti-drift), mesh, ring, star, adaptive-- **Consensus**: Raft (leader-based), Byzantine (PBFT), Gossip (eventual)-- **Hive-Mind**: Queen-led coordination with spawn, broadcast, consensus voting, shared memory-- **12 Background Workers**: audit, optimize, testgaps, map, deepdive, document, refactor, benchmark, ultralearn, consolidate, predict, preload--### Memory Capabilities--- **ONNX Embeddings**: all-MiniLM-L6-v2, 384 dimensions β real neural vectors-- **DiskANN**: SSD-friendly vector search (8,000x faster insert than HNSW, perfect recall at 1K)-- **sql.js**: Cross-platform SQLite (WASM, no native compilation)-- **Claude Code Bridge**: Auto-imports MEMORY.md files into AgentDB on session start-- **Unified Search**: \`memory_search_unified\` searches Claude memories + AgentDB + patterns-- **SONA Learning**: Trajectory recording β pattern extraction β file persistence+function intelligenceSystem(): string {+ return `## Intelligence (SONA + HNSW)-### How to Discover Tools+Pipeline: **RETRIEVE** (vector search) β **JUDGE** (success/failure) β **DISTILL** (extract patterns) β **CONSOLIDATE** (persist)-Use ToolSearch to find specific tools:-\`\`\`-ToolSearch("memory search") β memory_store, memory_search, memory_search_unified-ToolSearch("swarm") β swarm_init, swarm_status, swarm_health, swarm_shutdown-ToolSearch("hive consensus") β hive-mind_consensus, hive-mind_status-ToolSearch("+aidefence") β aidefence_scan, aidefence_is_safe, aidefence_has_pii-\`\`\``;+- **ONNX Embeddings**: all-MiniLM-L6-v2, 384-dim+- **HNSW/DiskANN**: 150x-12,500x faster search+- **SONA**: Sub-millisecond pattern adaptation+- **Claude Bridge**: Auto-imports \`~/.claude/projects/*/memory/*.md\` into AgentDB`;}-function setupAndBoundary(): string {- return `## Quick Setup+function federationRef(): string {+ return `## Federation++Cross-installation agent collaboration with zero-trust security.\`\`\`bash-claude mcp add claude-flow -- npx -y @claude-flow/cli@latest-npx @claude-flow/cli@latest daemon start-npx @claude-flow/cli@latest doctor --fix+npx @claude-flow/cli@latest federation init+npx @claude-flow/cli@latest federation join wss://peer:8443+npx @claude-flow/cli@latest federation send --to peer --type task-request --message "..."+npx @claude-flow/cli@latest federation status\`\`\`-## Claude Code vs MCP Tools--- **Claude Code Agent tool** handles execution: agents, file ops, code generation, git-- **MCP tools** (via ToolSearch) handle coordination: swarm, memory, hooks, routing, hive-mind-- **CLI commands** (via Bash) are the same tools with terminal output-- Use \`ToolSearch("keyword")\` to discover available MCP tools+- 5-tier trust: UNTRUSTED β VERIFIED β ATTESTED β TRUSTED β PRIVILEGED+- PII pipeline: 14 types auto-stripped before data leaves your node+- mTLS + ed25519 handshake, HMAC-signed envelopes+- Compliance: HIPAA, SOC2, GDPR audit modes`;+}-## Support+function envVars(): string {+ return `## Environment-- Documentation: https://github.com/ruvnet/ruflo-- Issues: https://github.com/ruvnet/ruflo/issues`;+\`\`\`bash+CLAUDE_FLOW_CONFIG=./claude-flow.config.json+CLAUDE_FLOW_LOG_LEVEL=info+CLAUDE_FLOW_MEMORY_BACKEND=hybrid+CLAUDE_FLOW_MEMORY_PATH=./data/memory+\`\`\``;}// --- Template Composers ----/**- * Template section map β defines which sections are included per template.- */const TEMPLATE_SECTIONS: Record<ClaudeMdTemplate, Array<(opts: InitOptions) => string>> = {minimal: [behavioralRules,- fileOrganization,- projectArchitecture,+ (_opts) => agentComms(),+ swarmConfig,(_opts) => buildAndTest(),- (_opts) => securityRulesLight(),- concurrencyRules,- (_opts) => antiDriftConfig(),- executionRules,- (_opts) => cliCommandsTable(),+ (_opts) => cliQuickRef(),(_opts) => setupAndBoundary(),],standard: [behavioralRules,- fileOrganization,- projectArchitecture,- (_opts) => buildAndTest(),- (_opts) => securityRulesLight(),- concurrencyRules,- (_opts) => swarmOrchestration(),- (_opts) => antiDriftConfig(),- executionRules,- (_opts) => cliCommandsTable(),+ (_opts) => agentComms(),+ swarmConfig,+ (_opts) => memoryAndLearning(),(_opts) => agentTypes(),- (_opts) => memoryCommands(),- (_opts) => mcpToolDiscovery(),+ (_opts) => buildAndTest(),+ (_opts) => cliQuickRef(),(_opts) => setupAndBoundary(),],full: [behavioralRules,- fileOrganization,- projectArchitecture,- (_opts) => buildAndTest(),- (_opts) => securityRulesLight(),- concurrencyRules,- (_opts) => swarmOrchestration(),- (_opts) => antiDriftConfig(),- (_opts) => autoStartProtocol(),- executionRules,- (_opts) => cliCommandsTable(),+ (_opts) => agentComms(),+ swarmConfig,+ (_opts) => memoryAndLearning(),(_opts) => agentTypes(),- (_opts) => hooksSystem(),- (_opts) => learningProtocol(),- (_opts) => memoryCommands(),- (_opts) => mcpToolDiscovery(),+ (_opts) => hooksRef(),(_opts) => intelligenceSystem(),+ (_opts) => federationRef(),+ (_opts) => buildAndTest(),(_opts) => envVars(),+ (_opts) => cliQuickRef(),(_opts) => setupAndBoundary(),],security: [behavioralRules,- fileOrganization,- projectArchitecture,- (_opts) => buildAndTest(),- concurrencyRules,- (_opts) => swarmOrchestration(),- (_opts) => antiDriftConfig(),- executionRules,+ (_opts) => agentComms(),+ swarmConfig,(_opts) => securitySection(),- (_opts) => cliCommandsTable(),+ (_opts) => memoryAndLearning(),(_opts) => agentTypes(),- (_opts) => memoryCommands(),+ (_opts) => buildAndTest(),+ (_opts) => cliQuickRef(),(_opts) => setupAndBoundary(),],performance: [behavioralRules,- fileOrganization,- projectArchitecture,- (_opts) => buildAndTest(),- (_opts) => securityRulesLight(),- concurrencyRules,- (_opts) => swarmOrchestration(),- (_opts) => antiDriftConfig(),- executionRules,+ (_opts) => agentComms(),+ swarmConfig,(_opts) => performanceSection(),- (_opts) => cliCommandsTable(),+ (_opts) => memoryAndLearning(),(_opts) => agentTypes(),- (_opts) => memoryCommands(),(_opts) => intelligenceSystem(),+ (_opts) => buildAndTest(),+ (_opts) => cliQuickRef(),(_opts) => setupAndBoundary(),],solo: [behavioralRules,- fileOrganization,- projectArchitecture,+ (_opts) => agentComms(),+ (_opts) => memoryAndLearning(),(_opts) => buildAndTest(),- (_opts) => securityRulesLight(),- concurrencyRules,- executionRules,- (_opts) => cliCommandsTable(),- (_opts) => memoryCommands(),+ (_opts) => cliQuickRef(),(_opts) => setupAndBoundary(),],};// --- Public API ----/**- * 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;- const header = `# Claude Code Configuration - RuFlo V3\n`;+ const header = `# Ruflo β Claude Code Configuration\n`;const body = sections.map(fn => fn(options)).join('\n\n');return `${header}\n${body}\n`;}-/**- * 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)' },+ { name: 'minimal', description: 'Lean start β rules, agent comms, swarm config, CLI ref (~80 lines)' },+ { name: 'standard', description: 'Recommended β adds memory, learning, agent types (~140 lines)' },+ { name: 'full', description: 'Everything β hooks, intelligence, federation (~220 lines)' },+ { name: 'security', description: 'Security-focused β adds scanning, audit, threat agents' },+ { name: 'performance', description: 'Performance-focused β adds benchmarking, profiling, SONA' },+ { name: 'solo', description: 'Solo developer β comms, memory, no swarm (~90 lines)' },];export default generateClaudeMd;