CLAUDE.md
CLAUDE.mdCLAUDE.mdroot
Quality
84/100
Scores the file, not the repository.Length
8,575 words
167 headings · 42 code blocksRepository
67k
— · pushed 0 days agoLast changed
3 days ago
First indexed 3 days ago.1# Claude Code Configuration - Ruflo V323> Public release train: `@claude-flow/cli`, `claude-flow`, and `ruflo`.4> Use package manifests and the registry as version truth; do not copy stale5> version or capability counts into agent guidance.67## Behavioral Rules (Always Enforced)89- Do what has been asked; nothing more, nothing less10- NEVER create files unless they're absolutely necessary for achieving your goal11- ALWAYS prefer editing an existing file to creating a new one12- NEVER proactively create documentation files (*.md) or README files unless explicitly requested13- NEVER save working files, text/mds, or tests to the root folder14- Never continuously check status after spawning a swarm — wait for results15- ALWAYS read a file before editing it16- NEVER commit secrets, credentials, or .env files1718## Capability Brain and Governed Implementation1920Ruflo is the coordination ledger and policy decision point. Claude Code21executes code, tests, commands, and file changes. A Ruflo coordination call22records work; it does not perform the implementation.2324When registered, call25`guidance_brain({ mode: "recommend", task: "..." })` before complex Ruflo26work. Use its live registry rather than guessing tool names. Treat27`registered`, `configured`, `reachable`, `healthy`, and `authorized` as28separate facts. If unavailable, continue with compatible guidance tools, CLI29discovery, and these repository instructions.3031Use this loop: recall → inspect → route → plan → execute → test → validate →32benchmark → optimize → receipt → handoff → separately authorized publish.3334## File Organization3536- NEVER save to root folder — use the directories below37- Use `/src` for source code files38- Use `/tests` for test files39- Use `/docs` for documentation and markdown files40- Use `/config` for configuration files41- Use `/scripts` for utility scripts42- Use `/examples` for example code4344## Project Architecture4546- Follow Domain-Driven Design with bounded contexts47- Keep files under 500 lines48- Use typed interfaces for all public APIs49- Prefer TDD London School (mock-first) for new code50- Use event sourcing for state changes51- Ensure input validation at system boundaries5253### Key Packages5455| Package | Path | Purpose |56|---------|------|---------|57| `@claude-flow/cli` | `v3/@claude-flow/cli/` | CLI entry point (26 commands) |58| `@claude-flow/codex` | `v3/@claude-flow/codex/` | Dual-mode Claude + Codex collaboration |59| `@claude-flow/guidance` | `v3/@claude-flow/guidance/` | Governance control plane |60| `@claude-flow/hooks` | `v3/@claude-flow/hooks/` | 17 hooks + 12 workers |61| `@claude-flow/memory` | `v3/@claude-flow/memory/` | AgentDB + HNSW search |62| `@claude-flow/security` | `v3/@claude-flow/security/` | Input validation, CVE remediation |6364## Concurrent Automated Development6566- Parallelize independent research, tests, reviews, and non-overlapping67 implementation.68- Never allow two writers in one worktree. Give every writing agent an isolated69 worktree and explicit file ownership.70- Read-only agents may share a checkout; writing agents may not.71- Only the integration owner edits shared manifests and lockfiles or reconciles72 overlapping changes.73- Continue independent local work after spawning agents; wait only when a real74 dependency blocks progress. Do not repeatedly poll.75- A lease or work claim coordinates ownership; it never grants authority.76- Bind tests, benchmarks, policy decisions, and handoffs to an exact clean77 commit or immutable dirty-worktree snapshot.78- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose and79 evaluate candidates, but cannot self-promote or expand tools, network,80 secrets, spend, concurrency, or release authority.8182---8384## Swarm Orchestration8586- MUST initialize the swarm using MCP tools when starting complex tasks87- MUST spawn concurrent agents using Claude Code's Task tool88- Never use MCP tools alone for execution — Task tool agents do the actual work8990### MCP + Task Tool in SAME Message9192- MUST call MCP tools AND Task tool in ONE message for complex work93- Always call MCP first, then IMMEDIATELY call Task tool to spawn agents9495### 3-Tier Model Routing (ADR-026, ADR-143)9697| Tier | Handler | Latency | Cost | Use Cases |98|------|---------|---------|------|-----------|99| **1** | Deterministic codemod | ~1ms | $0 | Structural transforms with **no LLM**: `var-to-const`, `remove-console`, `add-logging` |100| **2** | Haiku | ~500ms | $0.0002 | Simple tasks, low complexity (<30%) |101| **3** | Sonnet/Opus | 2-5s | $0.003-0.015 | Complex reasoning, architecture, security (>30%) |102103- Always check for `[CODEMOD_AVAILABLE]` or `[TASK_MODEL_RECOMMENDATION]` before spawning agents104- When you see `[CODEMOD_AVAILABLE]`, call the `hooks_codemod` MCP tool (intent + file) — it applies the transform deterministically via the TypeScript compiler at $0, no LLM. Deterministic intents only: `var-to-const`, `remove-console`, `add-logging`105- `add-types`, `add-error-handling`, `async-await` need judgement and route to a model (Tier 2/3) — they are **not** $0 codemods (see ADR-143)106- Agent Booster (`agent-booster`) is a fast-apply merge engine for arbitrary LLM-produced edit snippets, not an intent-transform engine — it is **not** the Tier-1 path107108## Swarm Configuration & Anti-Drift109110### Anti-Drift Coding Swarm (PREFERRED DEFAULT)111112- ALWAYS use hierarchical topology for coding swarms113- Keep maxAgents at 6-8 for tight coordination114- Use specialized strategy for clear role boundaries115- Use `raft` consensus for hive-mind (leader maintains authoritative state)116- Run frequent checkpoints via `post-task` hooks117- Keep shared memory namespace for all agents118- Keep task cycles short with verification gates119120```javascript121mcp__ruv-swarm__swarm_init({122 topology: "hierarchical",123 maxAgents: 8,124 strategy: "specialized"125})126```127128## Dual-Mode Collaboration (Claude Code + Codex)129130This repository uses **dual-mode orchestration** to run Claude Code (🔵) and OpenAI Codex (🟢) workers in parallel with shared memory coordination. Both platforms collaborate on development tasks with cross-learning.131132### Why Dual-Mode?133134| Single Platform | Dual-Mode Collaboration |135|----------------|------------------------|136| One model's perspective | Two AI platforms cross-validating |137| Limited reasoning styles | Complementary strengths |138| No external verification | Built-in code review |139| Sequential workflows | Parallel execution |140141### Dual-Mode Swarm Protocol142143For complex tasks, spawn both Claude and Codex workers in parallel:144145```javascript146// STEP 1: Initialize dual-mode swarm147mcp__ruv-swarm__swarm_init({148 topology: "hierarchical",149 maxAgents: 8,150 strategy: "specialized"151})152153// STEP 2: Spawn BOTH platforms in parallel via Task tool154// 🔵 Claude Code workers (architecture, security, testing)155Task("Architect", "Design the implementation. Store design in memory namespace 'collaboration'.", "system-architect")156Task("Tester", "Write tests based on architect's design. Read from 'collaboration' namespace.", "tester")157Task("Reviewer", "Review code quality and security. Store findings in 'collaboration'.", "reviewer")158159// 🟢 Codex workers (implementation, optimization)160// Spawn via CLI for Codex platform161Bash("npx claude-flow-codex dual run --worker 'codex:coder:Implement the solution based on architect design' --namespace collaboration")162Bash("npx claude-flow-codex dual run --worker 'codex:optimizer:Optimize performance based on implementation' --namespace collaboration")163164// STEP 3: Coordinate via shared memory165Bash("npx claude-flow@v3alpha memory store --namespace collaboration --key 'task-context' --value '[task description]'")166```167168### Collaboration Templates (Pre-Built Pipelines)169170| Template | Workers | Pipeline |171|----------|---------|----------|172| `feature` | 🔵 Architect → 🟢 Coder → 🔵 Tester → 🟢 Reviewer | Full feature development |173| `security` | 🔵 Analyst → 🟢 Scanner → 🔵 Reporter | Security audit workflow |174| `refactor` | 🔵 Architect → 🟢 Refactorer → 🔵 Tester | Code modernization |175| `bugfix` | 🔵 Researcher → 🟢 Coder → 🔵 Tester | Bug investigation & fix |176177### Dual-Mode CLI Commands178179```bash180# Run a collaboration template181npx claude-flow-codex dual run feature --task "Add user authentication with OAuth"182npx claude-flow-codex dual run security --target "./src"183npx claude-flow-codex dual run refactor --target "./src/legacy"184185# Custom multi-platform swarm186npx claude-flow-codex dual run \187 --worker "claude:architect:Design the API structure" \188 --worker "codex:coder:Implement REST endpoints" \189 --worker "claude:tester:Write integration tests" \190 --worker "codex:reviewer:Review code quality" \191 --namespace "api-feature"192193# Check collaboration status194npx claude-flow-codex dual status195196# List available templates197npx claude-flow-codex dual templates198```199200### Shared Memory Coordination201202All workers share state via the `collaboration` namespace:203204```bash205# Store context for cross-platform sharing206npx claude-flow@v3alpha memory store --namespace collaboration --key "design-decisions" --value "..."207208# Search for patterns across all workers209npx claude-flow@v3alpha memory search --namespace collaboration --query "authentication patterns"210211# Retrieve specific findings212npx claude-flow@v3alpha memory retrieve --namespace collaboration --key "security-findings"213```214215### Cross-Platform Learning216217Both platforms learn from each other's outputs:218219```bash220# After successful collaboration, train patterns221npx claude-flow@v3alpha hooks post-task --task-id "dual-[id]" --success true --train-neural true222223# Store successful collaboration patterns224npx claude-flow@v3alpha memory store --namespace patterns --key "dual-mode-[pattern]" --value "[what worked]"225226# Transfer learnings to both platforms227npx claude-flow@v3alpha hooks transfer store --pattern "dual-collab-success"228```229230### Worker Dependency Levels231232Workers execute in dependency order:233234```235Level 0: [🔵 Architect] # No dependencies - runs first236Level 1: [🟢 Coder, 🔵 Tester] # Depends on Architect237Level 2: [🔵 Reviewer] # Depends on Coder + Tester238Level 3: [🟢 Optimizer] # Depends on Reviewer approval239```240241### Platform Strengths242243| Task Type | Preferred Platform | Reason |244|-----------|-------------------|--------|245| Architecture & Design | 🔵 Claude | Strong reasoning, system thinking |246| Implementation | 🟢 Codex | Fast code generation |247| Security Review | 🔵 Claude | Careful analysis, threat modeling |248| Performance Optimization | 🟢 Codex | Code-level optimizations |249| Testing Strategy | 🔵 Claude | Coverage analysis, edge cases |250| Refactoring | 🟢 Codex | Bulk code transformations |251252### Programmatic API253254```typescript255import { DualModeOrchestrator, CollaborationTemplates } from '@claude-flow/codex';256257const orchestrator = new DualModeOrchestrator({258 namespace: 'my-feature',259 memoryBackend: 'hybrid'260});261262// Use pre-built template263const workers = CollaborationTemplates.featureDevelopment('Add OAuth login');264265// Run collaboration266const results = await orchestrator.runCollaboration(workers, 'Implement OAuth feature');267268// Access shared memory269const designDocs = await orchestrator.getMemory('design-decisions');270```271272---273274## Swarm Protocols & Routing275276### Auto-Start Swarm Protocol277278When the user requests a complex task (multi-file changes, feature implementation, refactoring), **immediately execute this pattern in a SINGLE message:**279280```javascript281// STEP 1: Initialize swarm coordination via MCP282mcp__ruv-swarm__swarm_init({283 topology: "hierarchical",284 maxAgents: 8,285 strategy: "specialized"286})287288// STEP 2: Spawn NAMED agents concurrently — all in ONE message289// Each agent knows WHO to message next in the pipeline290Task({291 prompt: "Research requirements and codebase. SendMessage findings to 'architect' when done.",292 subagent_type: "researcher", name: "researcher", run_in_background: true293})294Task({295 prompt: "Wait for research from 'researcher'. Design implementation. SendMessage design to 'coder'.",296 subagent_type: "system-architect", name: "architect", run_in_background: true297})298Task({299 prompt: "Wait for design from 'architect'. Implement the solution. SendMessage code paths to 'tester'.",300 subagent_type: "coder", name: "coder", run_in_background: true301})302Task({303 prompt: "Wait for implementation from 'coder'. Write tests. SendMessage results to 'reviewer'.",304 subagent_type: "tester", name: "tester", run_in_background: true305})306Task({307 prompt: "Wait for test results from 'tester'. Review code quality and security. Report findings.",308 subagent_type: "reviewer", name: "reviewer", run_in_background: true309})310311// STEP 3: Kick off the pipeline312SendMessage({ to: "researcher", summary: "Start research", message: "[task description and context]" })313314// STEP 4: Batch todos315TodoWrite({ todos: [316 {content: "Research and analyze requirements", status: "in_progress", activeForm: "Researching"},317 {content: "Design architecture", status: "pending", activeForm: "Designing"},318 {content: "Implement solution", status: "pending", activeForm: "Implementing"},319 {content: "Write tests", status: "pending", activeForm: "Testing"},320 {content: "Review and finalize", status: "pending", activeForm: "Reviewing"}321]})322323// Pipeline flow via SendMessage:324// researcher ──→ architect ──→ coder ──→ tester ──→ reviewer325```326327### Agent Routing (Anti-Drift)328329| Code | Task | Agents |330|------|------|--------|331| 1 | Bug Fix | coordinator, researcher, coder, tester |332| 3 | Feature | coordinator, architect, coder, tester, reviewer |333| 5 | Refactor | coordinator, architect, coder, reviewer |334| 7 | Performance | coordinator, perf-engineer, coder |335| 9 | Security | coordinator, security-architect, auditor |336| 11 | Memory | coordinator, memory-specialist, perf-engineer |337| 13 | Docs | researcher, api-docs |338339**Codes 1-11: hierarchical/specialized (anti-drift). Code 13: mesh/balanced**340341### Task Complexity Detection342343**AUTO-INVOKE SWARM when task involves:**344- Multiple files (3+)345- New feature implementation346- Refactoring across modules347- API changes with tests348- Security-related changes349- Performance optimization350- Database schema changes351352**SKIP SWARM for:**353- Single file edits354- Simple bug fixes (1-2 lines)355- Documentation updates356- Configuration changes357- Quick questions/exploration358359## Project Configuration360361This project is configured with Claude Flow V3 (Anti-Drift Defaults):362- **Topology**: hierarchical (prevents drift via central coordination)363- **Max Agents**: 8 (smaller team = less drift)364- **Strategy**: specialized (clear roles, no overlap)365- **Consensus**: raft (leader maintains authoritative state)366- **Memory Backend**: hybrid (SQLite + AgentDB)367- **HNSW Indexing**: Enabled (measured ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force; ANN wins above the crossover)368- **Neural Learning**: Enabled (SONA)369370## V3 CLI Commands (26 Commands, 140+ Subcommands)371372### Core Commands373374| Command | Subcommands | Description |375|---------|-------------|-------------|376| `init` | 4 | Project initialization with wizard, presets, skills, hooks |377| `agent` | 8 | Agent lifecycle (spawn, list, status, stop, metrics, pool, health, logs) |378| `swarm` | 6 | Multi-agent swarm coordination and orchestration |379| `memory` | 11 | AgentDB memory with HNSW vector search (measured ~1.9x–4.7x vs brute force above crossover) |380| `mcp` | 9 | MCP server management and tool execution |381| `task` | 6 | Task creation, assignment, and lifecycle |382| `session` | 7 | Session state management and persistence |383| `config` | 7 | Configuration management and provider setup |384| `status` | 3 | System status monitoring with watch mode |385| `start` | 3 | Service startup and quick launch |386| `workflow` | 6 | Workflow execution and template management |387| `hooks` | 17 | Self-learning hooks + 12 background workers |388| `hive-mind` | 6 | Queen-led Byzantine fault-tolerant consensus |389390### Advanced Commands391392| Command | Subcommands | Description |393|---------|-------------|-------------|394| `daemon` | 5 | Background worker daemon (start, stop, status, trigger, enable) |395| `neural` | 5 | Neural pattern training (train, status, patterns, predict, optimize) |396| `security` | 6 | Security scanning (scan, audit, cve, threats, validate, report) |397| `performance` | 5 | Performance profiling (benchmark, profile, metrics, optimize, report) |398| `providers` | 5 | AI providers (list, add, remove, test, configure) |399| `plugins` | 5 | Plugin management (list, install, uninstall, enable, disable) |400| `deployment` | 5 | Deployment management (deploy, rollback, status, environments, release) |401| `embeddings` | 4 | Vector embeddings (embed, batch, search, init) — agentic-flow ONNX backend (speedup unverified, no benchmark) |402| `claims` | 4 | Claims-based authorization (check, grant, revoke, list) |403| `migrate` | 5 | V2 to V3 migration with rollback support |404| `process` | 4 | Background process management |405| `doctor` | 1 | System diagnostics with health checks |406| `completions` | 4 | Shell completions (bash, zsh, fish, powershell) |407408### Quick CLI Examples409410```bash411# Initialize project412npx claude-flow@v3alpha init --wizard413414# Start daemon with background workers415npx claude-flow@v3alpha daemon start416417# Spawn an agent418npx claude-flow@v3alpha agent spawn -t coder --name my-coder419420# Initialize swarm421npx claude-flow@v3alpha swarm init --v3-mode422423# Search memory (HNSW-indexed)424npx claude-flow@v3alpha memory search -q "authentication patterns"425426# System diagnostics427npx claude-flow@v3alpha doctor --fix428429# Security scan430npx claude-flow@v3alpha security scan --depth full431432# Performance benchmark433npx claude-flow@v3alpha performance benchmark --suite all434```435436## Headless Background Instances (claude -p)437438Use `claude -p` (print/pipe mode) to spawn headless Claude instances for parallel background work. These run non-interactively and return results to stdout.439440### Basic Usage441442```bash443# Single headless task444claude -p "Analyze the authentication module for security issues"445446# With model selection447claude -p --model haiku "Format this config file"448claude -p --model opus "Design the database schema for user management"449450# With output format451claude -p --output-format json "List all TODO comments in src/"452claude -p --output-format stream-json "Refactor the error handling in api.ts"453454# With budget limits455claude -p --max-budget-usd 0.50 "Run comprehensive security audit"456457# With specific tools allowed458claude -p --allowedTools "Read,Grep,Glob" "Find all files that import the auth module"459460# Skip permissions (sandboxed environments only)461claude -p --dangerously-skip-permissions "Fix all lint errors in src/"462```463464### Parallel Background Execution465466```bash467# Spawn multiple headless instances in parallel468claude -p "Analyze src/auth/ for vulnerabilities" &469claude -p "Write tests for src/api/endpoints.ts" &470claude -p "Review src/models/ for performance issues" &471wait # Wait for all to complete472473# With results captured474SECURITY=$(claude -p "Security audit of auth module" &)475TESTS=$(claude -p "Generate test coverage report" &)476PERF=$(claude -p "Profile memory usage in workers" &)477wait478echo "$SECURITY" "$TESTS" "$PERF"479```480481### Session Continuation482483```bash484# Start a task, resume later485claude -p --session-id "abc-123" "Start analyzing the codebase"486claude -p --resume "abc-123" "Continue with the test files"487488# Fork a session for parallel exploration489claude -p --resume "abc-123" --fork-session "Try approach A: event sourcing"490claude -p --resume "abc-123" --fork-session "Try approach B: CQRS pattern"491```492493### Key Flags494495| Flag | Purpose |496|------|---------|497| `-p, --print` | Non-interactive mode, print and exit |498| `--model <model>` | Select model (haiku, sonnet, opus) |499| `--output-format <fmt>` | Output: text, json, stream-json |500| `--max-budget-usd <amt>` | Spending cap per invocation |501| `--allowedTools <tools>` | Restrict available tools |502| `--append-system-prompt` | Add custom instructions |503| `--resume <id>` | Continue a previous session |504| `--fork-session` | Branch from resumed session |505| `--fallback-model <model>` | Auto-fallback if primary overloaded |506| `--permission-mode <mode>` | acceptEdits, bypassPermissions, plan, etc. |507| `--mcp-config <json>` | Load MCP servers from JSON |508509## Available Agents (60+ Types)510511### Core Development512`coder`, `reviewer`, `tester`, `planner`, `researcher`513514### V3 Specialized Agents515`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`516517### @claude-flow/security Module518CVE remediation, input validation, path security:519- `InputValidator` — Zod-based validation at boundaries520- `PathValidator` — Path traversal prevention521- `SafeExecutor` — Command injection protection522- `PasswordHasher` — bcrypt hashing523- `TokenGenerator` — Secure token generation524525### Token Optimizer (Agent Booster)526Integrates agentic-flow optimizations for 30-50% token reduction:527```typescript528import { getTokenOptimizer } from '@claude-flow/integration';529const optimizer = await getTokenOptimizer();530531// Compact context (32% fewer tokens)532const ctx = await optimizer.getCompactContext("auth patterns");533534// 352x faster edits = fewer retries535await optimizer.optimizedEdit(file, old, new, "typescript");536537// Optimal config (100% success rate)538const config = optimizer.getOptimalConfig(agentCount);539```540| Feature | Token Savings |541|---------|---------------|542| ReasoningBank retrieval | -32% |543| Agent Booster edits | -15% |544| Cache (95% hit rate) | -10% |545| Optimal batch size | -20% |546547### Swarm Coordination548`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`, `collective-intelligence-coordinator`, `swarm-memory-manager`549550### Consensus & Distributed551`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`, `consensus-builder`, `crdt-synchronizer`, `quorum-manager`, `security-manager`552553### Performance & Optimization554`perf-analyzer`, `performance-benchmarker`, `task-orchestrator`, `memory-coordinator`, `smart-agent`555556### GitHub & Repository557`github-modes`, `pr-manager`, `code-review-swarm`, `issue-tracker`, `release-manager`, `workflow-automation`, `project-board-sync`, `repo-architect`, `multi-repo-swarm`558559### SPARC Methodology560`sparc-coord`, `sparc-coder`, `specification`, `pseudocode`, `architecture`, `refinement`561562### Specialized Development563`backend-dev`, `mobile-dev`, `ml-developer`, `cicd-engineer`, `api-docs`, `system-architect`, `code-analyzer`, `base-template-generator`564565### Testing & Validation566`tdd-london-swarm`, `production-validator`567568## Agent Teams & Comms System569570Agent 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.571572### Architecture573574```575Team Lead (you)576 ├── SendMessage ←→ architect (named agent)577 ├── SendMessage ←→ developer (named agent)578 ├── SendMessage ←→ tester (named agent)579 └── SendMessage ←→ reviewer (named agent)580 ↕ agents can message each other by name581```582583### Core Principle: Named Agents + SendMessage584585Every agent MUST have a `name` so it's addressable. Communication happens via `SendMessage`, not polling or shared memory.586587```javascript588// STEP 1: Spawn named agents (all in ONE message, background)589Task({590 prompt: "Design the API. When done, send your design to 'developer' via SendMessage.",591 subagent_type: "system-architect",592 name: "architect",593 run_in_background: true594})595Task({596 prompt: "Wait for architect's design via SendMessage. Then implement it. Send code to 'tester'.",597 subagent_type: "coder",598 name: "developer",599 run_in_background: true600})601Task({602 prompt: "Wait for developer's code via SendMessage. Write tests. Send results to 'reviewer'.",603 subagent_type: "tester",604 name: "tester",605 run_in_background: true606})607608// STEP 2: Kick off the pipeline by messaging the first agent609SendMessage({610 to: "architect",611 summary: "Start API design",612 message: "Design a REST API for user management with CRUD endpoints. Send the design to 'developer' when done."613})614```615616### SendMessage Protocol617618```javascript619// Lead → Teammate: assign work620SendMessage({ to: "developer", summary: "Implement auth", message: "Build OAuth2 flow..." })621622// Lead → Teammate: redirect priorities623SendMessage({ to: "developer", summary: "Prioritize auth", message: "Auth endpoint is blocking tester, do it first." })624625// Lead → Teammate: provide context from another agent's results626SendMessage({ to: "tester", summary: "Architect output", message: "The architect designed these endpoints: [details]. Write tests for them." })627628// Lead → Teammate: graceful shutdown629SendMessage({ to: "developer", message: { type: "shutdown_request" } })630```631632### Coordination Patterns633634**Pipeline (A → B → C)** — each agent messages the next when done:635```636architect ──SendMessage──→ developer ──SendMessage──→ tester ──SendMessage──→ reviewer637```638Tell each agent WHO to message next in their prompt.639640**Fan-out / Fan-in** — lead spawns parallel agents, collects results:641```642 ┌→ researcher-1 ──→┐643lead ────┼→ researcher-2 ──→├──→ lead synthesizes644 └→ researcher-3 ──→┘645```646Spawn with `run_in_background: true`. Results arrive as task completions.647648**Supervisor / Worker** — lead assigns, workers report back:649```650lead ←──SendMessage──→ worker-1651lead ←──SendMessage──→ worker-2652lead ←──SendMessage──→ worker-3653```654Lead sends tasks via SendMessage, workers respond with results.655656### Agent Prompt Template (Comms-Aware)657658When spawning agents that need to coordinate, include comms instructions:659660```javascript661Task({662 prompt: `You are the architect for this feature team.663664YOUR TASK: Design the database schema for user management.665666COMMS PROTOCOL:667- When your design is ready, send it to "developer" via SendMessage668- If you need clarification, message the team lead (just output text)669- Include file paths and key decisions in your message670671DELIVERABLE: Schema design with entity relationships, indexes, and migration plan.`,672 subagent_type: "system-architect",673 name: "architect",674 run_in_background: true675})676```677678### Full Team Spawn Example679680```javascript681// Create shared task list first682TaskCreate({ subject: "Design schema", description: "...", activeForm: "Designing" })683TaskCreate({ subject: "Implement models", description: "...", activeForm: "Implementing" })684TaskCreate({ subject: "Write tests", description: "...", activeForm: "Testing" })685TaskCreate({ subject: "Security review", description: "...", activeForm: "Reviewing" })686687// Spawn ALL named agents in ONE message688Task({689 prompt: "Design the schema. SendMessage to 'developer' with your design when done. Update task #1.",690 subagent_type: "system-architect", name: "architect", run_in_background: true691})692Task({693 prompt: "Wait for schema from 'architect'. Implement models + endpoints. SendMessage to 'tester'. Update task #2.",694 subagent_type: "coder", name: "developer", run_in_background: true695})696Task({697 prompt: "Wait for code from 'developer'. Write integration tests. SendMessage results to 'security'. Update task #3.",698 subagent_type: "tester", name: "tester", run_in_background: true699})700Task({701 prompt: "Wait for test results from 'tester'. Review for vulnerabilities. Update task #4.",702 subagent_type: "security-auditor", name: "security", run_in_background: true703})704```705706### Agent Teams Hooks707708| Hook | Trigger | Purpose |709|------|---------|---------|710| `TeammateIdle` | Teammate finishes turn | Auto-assign pending tasks via SendMessage |711| `TaskCompleted` | Task marked complete | Train patterns, notify lead via SendMessage |712713```bash714npx claude-flow@v3alpha hooks teammate-idle --auto-assign true715npx claude-flow@v3alpha hooks task-completed -i task-123 --train-patterns true716```717718### Rules7197201. **Always name agents** — use `name: "role-name"` so they're addressable7212. **Comms over memory** — use SendMessage for real-time coordination, memory for persistence7223. **Pipeline prompts** — tell each agent WHO to message next and WHAT to send7234. **Spawn all at once** — all Task calls in ONE message with `run_in_background: true`7245. **Don't poll** — agents message back when done; wait for task completion notifications7256. **Graceful shutdown** — send `{ type: "shutdown_request" }` before TeamDelete7267. **Lead synthesizes** — when agents complete, review ALL results before responding to user727728## V3 Hooks System (17 Hooks + 12 Workers)729730### Hook Categories731732| Category | Hooks | Purpose |733|----------|-------|---------|734| **Core** | `pre-edit`, `post-edit`, `pre-command`, `post-command`, `pre-task`, `post-task` | Tool lifecycle |735| **Session** | `session-start`, `session-end`, `session-restore`, `notify` | Context management |736| **Intelligence** | `route`, `explain`, `pretrain`, `build-agents`, `transfer` | Neural learning |737| **Learning** | `intelligence` (trajectory-start/step/end, pattern-store/search, stats, attention) | Reinforcement |738| **Agent Teams** | `teammate-idle`, `task-completed` | Multi-agent coordination |739740### 12 Background Workers741742| Worker | Priority | Description |743|--------|----------|-------------|744| `ultralearn` | normal | Deep knowledge acquisition |745| `optimize` | high | Performance optimization |746| `consolidate` | low | Memory consolidation |747| `predict` | normal | Predictive preloading |748| `audit` | critical | Security analysis |749| `map` | normal | Codebase mapping |750| `preload` | low | Resource preloading |751| `deepdive` | normal | Deep code analysis |752| `document` | normal | Auto-documentation |753| `refactor` | normal | Refactoring suggestions |754| `benchmark` | normal | Performance benchmarking |755| `testgaps` | normal | Test coverage analysis |756757### Essential Hook Commands758759```bash760# Core hooks761npx claude-flow@v3alpha hooks pre-task --description "[task]"762npx claude-flow@v3alpha hooks post-task --task-id "[id]" --success true763npx claude-flow@v3alpha hooks post-edit --file "[file]" --train-patterns764765# Session management766npx claude-flow@v3alpha hooks session-start --session-id "[id]"767npx claude-flow@v3alpha hooks session-end --export-metrics true768npx claude-flow@v3alpha hooks session-restore --session-id "[id]"769770# Intelligence routing771npx claude-flow@v3alpha hooks route --task "[task]"772npx claude-flow@v3alpha hooks explain --topic "[topic]"773774# Neural learning775npx claude-flow@v3alpha hooks pretrain --model-type moe --epochs 10776npx claude-flow@v3alpha hooks build-agents --agent-types coder,tester777778# Background workers779npx claude-flow@v3alpha hooks worker list780npx claude-flow@v3alpha hooks worker dispatch --trigger audit781npx claude-flow@v3alpha hooks worker status782```783784## Intelligence System (RuVector)785786V3 includes the RuVector Intelligence System (measured numbers: see [audit](docs/reviews/intelligence-system-audit-2026-05-29.md) + [`scripts/benchmark-intelligence.mjs`](scripts/benchmark-intelligence.mjs)):787- **SONA**: Self-Optimizing Neural Architecture (measured 0.0043ms/adapt, target <0.05ms met)788- **MoE**: Mixture of Experts for specialized routing (gate converges — confidence 0.13→0.88 after rewards)789- **HNSW**: measured ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force (recall@10 ~0.99); ANN wins above the crossover, ruvector NAPI backend (WASM not active on test host)790- **EWC++**: Elastic Weight Consolidation (prevents forgetting)791- **Flash Attention**: integration available; speedup dropped from docs pending an in-tree benchmark (was: 2.49x–7.47x, inherited unverified from upstream — removed to avoid a credibility claim we can't reproduce)792793The 4-step intelligence pipeline:7941. **RETRIEVE** — Fetch relevant patterns via HNSW7952. **JUDGE** — Evaluate with verdicts (success/failure)7963. **DISTILL** — Extract key learnings via LoRA7974. **CONSOLIDATE** — Prevent catastrophic forgetting via EWC++798799## Embeddings Package (v3.0.0-alpha.12)800801Features:802- **sql.js**: Cross-platform SQLite persistent cache (WASM, no native compilation)803- **Document chunking**: Configurable overlap and size804- **Normalization**: L2, L1, min-max, z-score805- **Hyperbolic embeddings**: Poincare ball model for hierarchical data806- **agentic-flow ONNX integration**: speedup unverified (no benchmark; backend reported `onnx`, model all-MiniLM-L6-v2, 384-dim)807- **Neural substrate**: Integration with RuVector808809## Hive-Mind Consensus810811### Topologies812- `hierarchical` — Queen controls workers directly813- `mesh` — Fully connected peer network814- `hierarchical-mesh` — Hybrid (recommended)815- `adaptive` — Dynamic based on load816817### Consensus Strategies818- `byzantine` — BFT (tolerates f < n/3 faulty)819- `raft` — Leader-based (tolerates f < n/2)820- `gossip` — Epidemic for eventual consistency821- `crdt` — Conflict-free replicated data types822- `quorum` — Configurable quorum-based823824## V3 Performance Targets825826> Source of truth: [`docs/reviews/intelligence-system-audit-2026-05-29.md`](docs/reviews/intelligence-system-audit-2026-05-29.md) + [`scripts/benchmark-intelligence.mjs`](scripts/benchmark-intelligence.mjs). Numbers below are measured unless marked "target/unverified".827828| Metric | Measured / Target | Status |829|--------|-------------------|--------|830| HNSW Search | ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force (recall@10 ~0.99); ties/loses below crossover | **Measured** (ruvector NAPI; 150x-12,500x NOT reproduced — was brute-force fallback) |831| Int8 Quantization | 3.84x compression, reconstruction cosine 0.99999 | **Measured** |832| RaBitQ Quantization | 32x compression, 0.60ms/query (14,760-vec index) | **Measured** |833| SONA Adaptation | 0.0043ms/adapt (target <0.05ms met) | **Measured** |834| MoE Gate | converges — confidence 0.13→0.88, Q 0→99.8 after rewards | **Measured** |835| Flash Attention | integration available; measured speedup pending benchmark | **Not measured** — prior "2.49x–7.47x" figure was inherited from upstream marketing, never reproduced in-tree; dropped to avoid a credibility claim we can't verify |836| MCP Response | <100ms | target |837| CLI Startup | <500ms | target |838839## Environment Variables840841```bash842# Configuration843CLAUDE_FLOW_CONFIG=./claude-flow.config.json844CLAUDE_FLOW_LOG_LEVEL=info845846# Provider API Keys847ANTHROPIC_API_KEY=sk-ant-...848OPENAI_API_KEY=sk-...849GOOGLE_API_KEY=...850851# MCP Server852CLAUDE_FLOW_MCP_PORT=3000853CLAUDE_FLOW_MCP_HOST=localhost854CLAUDE_FLOW_MCP_TRANSPORT=stdio855856# Memory857CLAUDE_FLOW_MEMORY_BACKEND=hybrid858CLAUDE_FLOW_MEMORY_PATH=./data/memory859```860861## Doctor Health Checks862863Run `npx claude-flow@v3alpha doctor` to check:864- Node.js version (20+)865- npm version (9+)866- Git installation867- Config file validity868- Daemon status869- Memory database870- API keys871- MCP servers872- Disk space873- TypeScript installation874875## Quick Setup876877```bash878# Add MCP servers879claude mcp add claude-flow -- npx -y ruflo@latest mcp start880claude mcp add ruv-swarm npx ruv-swarm mcp start # Optional881claude mcp add flow-nexus npx flow-nexus@latest mcp start # Optional882883# Start daemon884npx claude-flow@v3alpha daemon start885886# Run doctor887npx claude-flow@v3alpha doctor --fix888```889890## Claude Code vs MCP Tools891892### Claude Code Handles ALL EXECUTION:893- **Task tool**: Spawn and run agents concurrently894- File operations (Read, Write, Edit, MultiEdit, Glob, Grep)895- Code generation and programming896- Bash commands and system operations897- TodoWrite and task management898- Git operations899900### MCP Tools ONLY COORDINATE:901- Swarm initialization (topology setup)902- Agent type definitions903- Task orchestration904- Memory management905- Neural features906- Performance tracking907908- Keep MCP for coordination strategy only — use Claude Code's Task tool for real execution909910## Claude Code ↔ AgentDB Memory Bridge911912Claude Code's auto-memory (`~/.claude/projects/*/memory/*.md`) is bridged to AgentDB with ONNX vector embeddings for semantic search.913914### MCP Tools915916| Tool | Description |917|------|-------------|918| `memory_import_claude` | Import Claude Code memories into AgentDB with 384-dim ONNX embeddings. Use `allProjects: true` to import from ALL projects. |919| `memory_bridge_status` | Show bridge health — Claude files, AgentDB entries, SONA state, connection status |920| `memory_search_unified` | Semantic search across ALL namespaces (claude-memories, auto-memory, patterns, tasks, feedback) |921922### Auto-Import on Session Start923924The `SessionStart` hook automatically imports current project's memories into AgentDB. For manual import of all projects:925926```bash927# Via MCP tool (from Claude Code)928memory_import_claude({ allProjects: true })929930# Via helper hook (from terminal)931node .claude/helpers/auto-memory-hook.mjs import-all932```933934### Unified Search935936Search across both Claude Code memories and AgentDB entries:937938```bash939# Via MCP tool940memory_search_unified({ query: "authentication security", limit: 5 })941942# Results include source attribution: claude-code, auto-memory, or agentdb943```944945### Intelligence Pipeline946947| Component | Status | Details |948|-----------|--------|---------|949| ONNX Embeddings | Active | all-MiniLM-L6-v2, 384 dimensions |950| SONA Learning | Active | Pattern matching + trajectory recording |951| ReasoningBank | Active | Pattern storage with file persistence |952| AgentDB sql.js | Active | SQLite with vector_indexes table |953954## Publishing to npm955956### Versioning policy (stable releases — alpha series ended at 3.7.0-alpha.81, 2026-05-23)957958- **From 3.7.0 onward we ship stable semver**, NOT alpha pre-releases.959- Bump rules (semver discipline):960 - **PATCH** (3.7.0 → 3.7.1): bug fixes only, no API change, no schema change961 - **MINOR** (3.7.0 → 3.8.0): backward-compatible additions (new MCP tool, new flag, new agent type)962 - **MAJOR** (3.x → 4.0.0): breaking change in CLI surface, MCP tool signature, file layout, or default behavior963- Default tag is `latest` (no `--tag alpha`). The `alpha` and `v3alpha` dist-tags continue to exist for historical compatibility — point them at the same version as `latest`.964- Never publish a pre-release (`-alpha.N`, `-beta.N`, `-rc.N`) unless the user explicitly asks for a pre-release flow.965966### Publishing Rules967968- The normal public release train is exactly THREE packages:969 `@claude-flow/cli`, `claude-flow`, and `ruflo`.970- Internal `@claude-flow/*` components are bundled into the public artifacts;971 do not publish them standalone as part of the normal release.972- MUST update ALL dist-tags for ALL THREE packages after publishing (latest + alpha + v3alpha all point to the same version)973- Publish order: `@claude-flow/cli` first, then `claude-flow` (umbrella), then `ruflo` (alias umbrella)974- MUST run verification for ALL THREE before telling user publishing is complete975- Run `node scripts/audit-umbrella-version-lockstep.mjs` before packing or976 publishing.977- Publish from a clean reviewed commit/tag-equivalent worktree. Do not ship978 unrelated uncommitted changes.979- A fresh worktree has two separate dependency trees to install before anything980 builds: `npm install` at repo root (npm workspaces), AND `pnpm install` inside981 `v3/` (a separate pnpm workspace — root `prepare-root-publish.mjs` shells out to982 `pnpm --filter` to build `v3/@claude-flow/{shared,hooks,guidance}`, which fails983 with `spawn ENOENT` on `tsc` if `v3/node_modules` was never populated).984- Use the existing authenticated `ruvnet` npm session. Do not replace it with a985 token from another GCP project.986987**`npm publish` auth — FIXED (2026-07-30):** use the `NPM_TOKEN` secret directly,988via a throwaway `.npmrc` with `NPM_CONFIG_USERCONFIG` — same pattern as the989helpers-signing-key handling. It is mirrored in two GCP projects — `ruv-dev`990(version 3+) and `cognitum-20260110` (version 7+) — so either project's copy991is current; use whichever `gcloud` session is already authenticated. This is a992granular access token ("ruflo publishjing", expires 2026-10-28) with993`package: write` + `bypass_2fa: true`, scoped broadly enough to cover994`@claude-flow/cli`, `claude-flow`, and `ruflo` (plus the `cognitum`/995`cognitum-one` orgs). Confirmed end-to-end against the real registry (not just996a permissions probe): `npm publish` for `@claude-flow/cli` succeeded via this997token with zero OTP/WebAuthn prompt, and998`npm dist-tag add` against both a scoped (`@claude-flow/cli`) and unscoped999(`claude-flow`) package also went through with no prompt.10001001**Why the earlier `NPM_TOKEN` version failed:** versions 1/2 of that secret1002were older classic automation tokens, and npm has been restricting tokens that1003bypass 2FA for writes account-wide (the login flow prints this notice —1004`gh.io/npm-gat-bypass2fa-deprecation`). Version 3 is a **granular access1005token** created explicitly for this purpose, which is npm's supported1006replacement path (its own 2FA-bypass flag still works for a granular token,1007unlike the deprecated classic automation tokens). If this token's `bypass_2fa`1008flag or scope ever gets narrowed/expired (check expiry above), the fallback1009is the WebAuthn dance below — but try this path first every time.10101011```bash1012gcloud secrets versions access latest --secret=NPM_TOKEN --project=ruv-dev > /tmp/.npmrc-publish-raw1013printf '//registry.npmjs.org/:_authToken=%s\n' "$(cat /tmp/.npmrc-publish-raw)" > /tmp/.npmrc-publish1014rm -f /tmp/.npmrc-publish-raw1015NPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm publish # from the package dir, with signing-key env vars for @claude-flow/cli1016NPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> alpha1017NPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> v3alpha1018shred -u /tmp/.npmrc-publish 2>/dev/null || rm -f /tmp/.npmrc-publish # ALWAYS clean up, same discipline as the signing key1019```10201021**Fallback — WebAuthn procedure, if the token above is dead:** the `ruvnet`1022account's 2FA method is a WebAuthn security key, not TOTP (no numeric1023`--otp=<code>` exists). This must be driven by the human (an agent cannot1024approve a WebAuthn browser prompt):10251. Human goes to npmjs.com → account 2FA settings → turns OFF "Require1026 two-factor authentication for write actions" (narrows to auth-only, not a1027 full 2FA disable), then runs `npm login` in their own terminal to refresh1028 the session under the new setting.10292. Agent can then run `npm publish` directly via Bash with no further prompt.10303. **`npm dist-tag add` still requires a fresh WebAuthn approval PER CALL**1031 regardless of the write-2FA setting — 6 individual browser approvals for a1032 3-package release (alpha + v3alpha × 3), not 1. Tell the human up front.1033- After every dist-tag call (or if unsure), verify with1034 `npm view <pkg> dist-tags --json` — don't trust the CLI's own stdout alone, since1035 a WebAuthn prompt that's still pending in the browser produces no terminal1036 output an agent can see.1037- Confirm the version actually landed (`npm view <pkg>@<version> version`) before1038 telling the user publishing succeeded, same reasoning: a mid-publish approval1039 that never gets answered fails silently from an agent's point of view.10401041**Helpers signing key (required for `@claude-flow/cli` publish):** `npm publish`'s1042`prepublishOnly` runs `scripts/sign-helpers.mjs`, which needs a private key to sign1043`.claude/helpers/helpers.manifest.json`. The secret lives in GCP Secret Manager in the1044**`ruv-dev`** project (not `cognitum-20260110` or `claude-flow` — checked both, not there),1045secret name `ruflo-helpers-signing-key`:10461047```bash1048cd v3/@claude-flow/cli1049RUFLO_HELPERS_SIGNING_SECRET=ruflo-helpers-signing-key RUFLO_HELPERS_SIGNING_PROJECT=ruv-dev \1050 npm publish1051```10521053(`ruv-dev` also holds `ruflo-config-signing-key`; do not replace the existing1054authenticated npm session with a token from another project.)10551056**Handling the signing key without leaking it (learned 2026-07-14, hard way):**1057an earlier Windows path invoked `gcloud` without its required `.cmd` suffix. The1058fallback command printed the PEM into captured tool output and a session transcript.1059GCP secret v1 was destroyed and a fresh v2 was rotated in (commit 0052b1b06 /1060PR #2673). `sign-helpers.mjs` now selects `gcloud.cmd` on Windows and supports a1061stdin-only fallback. **Rules:**1062- NEVER invoke `gcloud secrets versions access` in a way that lets the payload reach1063 tool output. Use the built-in `RUFLO_HELPERS_SIGNING_SECRET` path above, or pipe1064 directly into the signer:1065 `gcloud secrets versions access latest --secret=ruflo-helpers-signing-key --project=ruv-dev | node scripts/sign-helpers.mjs --stdin-key`.1066- `--stdin-key` refuses interactive entry, validates Ed25519 key type, and never1067 echoes parser input. A local file via `RUFLO_HELPERS_SIGNING_KEY` remains the1068 air-gapped fallback.1069- If a rotation IS needed, keep the private half in `~/.ruflo/helpers-signing.key`1070 only, print ONLY the public half (via `Ed25519 pub export` from Node crypto), upload1071 new private via `gcloud secrets versions add … --data-file=`, then1072 `gcloud secrets versions destroy <old>` to make the old irrecoverable.10731074**Windows `prepublishOnly` failure (learned 2026-07-14):** the CLI's `prepublishOnly`1075chain (`cp ../../../README.md ./README.md && rm -rf plugins && mkdir -p plugins && cp -r ...`)1076is POSIX-shell-only. On Windows, npm runs it via `cmd.exe /d /s /c` which chokes on1077`mkdir -p` (interprets `-p` as a directory name) and `cp -r` (no such command). Two1078workarounds until the script is rewritten in cross-platform Node:10791. Run the prep steps manually in Git Bash, then `npm publish --ignore-scripts`.10802. Or use a POSIX shell for the whole publish: `SHELL=bash npm publish` — but this1081 doesn't always take effect on Windows depending on npm version.1082Option 1 is what worked for v3.29.0. Track proper fix in ruvnet/ruflo issue for1083cross-platform prepublish.10841085**Concurrent-session helper corruption (real, observed, be paranoid):** multiple Claude Code1086sessions can have their own `npm exec @claude-flow/cli@latest mcp start` MCP server running1087concurrently with `cwd` inside this repo (check with `readlink /proc/<pid>/cwd` on1088`pgrep -f "npm exec @claude-flow/cli@latest mcp start"`). If one of those resolved an older1089cached `@latest` (predating the `semver.gte` downgrade-guard in1090`helper-refresh.ts:autoRefreshHelpersIfStale`), it will silently overwrite this repo's1091hand-maintained `.claude/helpers/hook-handler.cjs` / `intelligence.cjs` (root AND package1092copies) — and `helpers.manifest.json` + `.helpers-version` — with its own older bundled1093content, mid-session, with no warning. Observed live 2026-07-13: this happened *twice* in1094one publish flow, once right after a manual revert and once right after signing (silently1095invalidating a freshly-signed manifest). **Mitigation:** never trust the on-disk state of1096those files between tool calls — `git diff --stat` them immediately before any `git add`/1097`sign-helpers.mjs`/`npm publish` step, `git checkout HEAD --` revert if dirty, and chain1098revert → sign → verify → add → commit as ONE bash invocation (`&&`-joined) to minimize the1099race window. `npm publish`'s own `prepublishOnly` re-signs fresh at pack time regardless, so1100what matters is the on-disk state at the *exact moment* `npm publish` runs, not before.11011102```bash1103# Replace 3.7.1 below with your chosen stable version (patch/minor/major per the rules above)11041105# STEP 1: Build and publish @claude-flow/cli1106cd v3/@claude-flow/cli1107npm version 3.7.1 --no-git-tag-version1108npm run build1109npm publish # default tag is `latest` — no --tag flag1110npm dist-tag add @claude-flow/cli@3.7.1 alpha # historical compat1111npm dist-tag add @claude-flow/cli@3.7.1 v3alpha # historical compat11121113# STEP 2: Publish claude-flow umbrella1114cd /Users/cohen/Projects/ruflo # or your repo root1115npm version 3.7.1 --no-git-tag-version1116npm publish1117npm dist-tag add claude-flow@3.7.1 alpha1118npm dist-tag add claude-flow@3.7.1 v3alpha11191120# STEP 3: Publish ruflo wrapper (CRITICAL — DON'T FORGET — this is what users run)1121cd ruflo1122npm version 3.7.1 --no-git-tag-version1123npm publish1124npm dist-tag add ruflo@3.7.1 alpha1125npm dist-tag add ruflo@3.7.1 v3alpha1126```11271128**Verification (run before telling user publishing is complete):**11291130```bash1131for pkg in @claude-flow/cli claude-flow ruflo; do1132 echo "$pkg: $(npm view $pkg@latest version)"1133 npm view $pkg dist-tags --json1134done1135# All three must show latest === alpha === v3alpha === new version1136```11371138### All Tags That Must Be Updated11391140| Package | Tag | Command Users Run |1141|---------|-----|-------------------|1142| `@claude-flow/cli` | `latest` | `npx @claude-flow/cli@latest` |1143| `@claude-flow/cli` | `alpha` | `npx @claude-flow/cli@alpha` (legacy compat) |1144| `@claude-flow/cli` | `v3alpha` | `npx @claude-flow/cli@v3alpha` (legacy compat) |1145| `claude-flow` | `latest` | `npx claude-flow@latest` |1146| `claude-flow` | `alpha` | `npx claude-flow@alpha` (legacy compat) |1147| `claude-flow` | `v3alpha` | `npx claude-flow@v3alpha` (legacy compat) |1148| `ruflo` | `latest` | `npx ruflo@latest` |1149| `ruflo` | `alpha` | `npx ruflo@alpha` (legacy compat) |1150| `ruflo` | `v3alpha` | `npx ruflo@v3alpha` (legacy compat) |11511152- Never forget the `ruflo` package — it's the thin wrapper users actually run via `npx ruflo`1153- The legacy `alpha` and `v3alpha` tags MUST stay pointed at the latest stable so old install commands keep working1154- `ruflo` source is in `/ruflo/` — it depends on `@claude-flow/cli`1155- Also remember to update `ruflo/package.json` overrides when adding new pinned transitives (see #2112 lesson — root overrides do NOT propagate to the published `ruflo` wrapper)11561157### GitHub Release after publish11581159Every stable bump SHOULD have a matching `gh release create v<version>` with consolidated release notes pointing at the gist if one exists. Example:11601161```bash1162git tag v3.7.1 main1163git push origin v3.7.11164gh release create v3.7.1 --title "v3.7.1 — <one-line headline>" \1165 --notes-file /tmp/release-notes.md1166```11671168## Plugin Registry Maintenance (IPFS/Pinata)11691170The plugin registry is stored on IPFS via Pinata for decentralized, immutable distribution.11711172### Registry Location1173- **Current CID**: Stored in `v3/@claude-flow/cli/src/plugins/store/discovery.ts`1174- **Gateway**: `https://gateway.pinata.cloud/ipfs/{CID}`1175- **Format**: JSON with plugin metadata, categories, featured/trending lists11761177### Required Environment Variables1178Add to `.env` (NEVER commit actual values):1179```bash1180PINATA_API_KEY=your-api-key1181PINATA_API_SECRET=your-api-secret1182PINATA_API_JWT=your-jwt-token1183```11841185## Plugin Registry Operations11861187### Adding a New Plugin to Registry118811891. **Fetch current registry**:1190```bash1191curl -s "https://gateway.pinata.cloud/ipfs/$(grep LIVE_REGISTRY_CID v3/@claude-flow/cli/src/plugins/store/discovery.ts | cut -d"'" -f2)" > /tmp/registry.json1192```119311942. **Add plugin entry** to the `plugins` array:1195```json1196{1197 "id": "@claude-flow/your-plugin",1198 "name": "@claude-flow/your-plugin",1199 "displayName": "Your Plugin",1200 "description": "Plugin description",1201 "version": "1.0.0-alpha.1",1202 "size": 100000,1203 "checksum": "sha256:abc123",1204 "author": {"id": "claude-flow-team", "displayName": "Claude Flow Team", "verified": true},1205 "license": "MIT",1206 "categories": ["official"],1207 "tags": ["your", "tags"],1208 "downloads": 0,1209 "rating": 5,1210 "lastUpdated": "2026-01-25T00:00:00.000Z",1211 "minClaudeFlowVersion": "3.0.0",1212 "type": "integration",1213 "hooks": [],1214 "commands": [],1215 "permissions": ["memory"],1216 "exports": ["YourExport"],1217 "verified": true,1218 "trustLevel": "official"1219}1220```122112223. **Update counts and arrays**:1223 - Increment `totalPlugins`1224 - Add to `official` array1225 - Add to `featured`/`newest` if applicable1226 - Update category `pluginCount`122712284. **Upload to Pinata** (read credentials from .env):1229```bash1230# Source credentials from .env1231PINATA_JWT=$(grep "^PINATA_API_JWT=" .env | cut -d'=' -f2-)12321233# Upload updated registry1234curl -X POST "https://api.pinata.cloud/pinning/pinJSONToIPFS" \1235 -H "Authorization: Bearer $PINATA_JWT" \1236 -H "Content-Type: application/json" \1237 -d @/tmp/registry.json1238```123912405. **Update discovery.ts** with new CID:1241```typescript1242export const LIVE_REGISTRY_CID = 'NEW_CID_FROM_PINATA';1243```124412456. **Also update demo registry** in discovery.ts `demoPluginRegistry` for offline fallback12461247### Security Rules1248- NEVER hardcode API keys in scripts or source files1249- NEVER commit .env (already in .gitignore)1250- Always source credentials from environment at runtime1251- Always delete temporary scripts after one-time uploads12521253### Verification1254```bash1255# Verify new registry is accessible1256curl -s "https://gateway.pinata.cloud/ipfs/{NEW_CID}" | jq '.totalPlugins'1257```12581259## MetaHarness Integration (ADR-150)12601261Ruflo integrates with the upstream `metaharness` / `@metaharness/*` ecosystem as a sibling agent-harness scaffolding system (same author, designed around ruflo's primitives). MetaHarness packages are optional peer dependencies and are never required at runtime.12621263### Architectural constraint (load-bearing)12641265**Ruflo remains operational if every MetaHarness package is removed.** Four rules:12661. **Removable**: `npm ls --without @metaharness/*` must still produce a working CLI12672. **Optional in package.json**: `@metaharness/*` packages MUST be optional peers, never normal dependencies12683. **Graceful degradation**: every code path that touches MetaHarness catches `MODULE_NOT_FOUND` and falls back12694. **CI gate**: `.github/workflows/no-metaharness-smoke.yml` enforces all three by static grep + runtime drill on every PR12701271### Command + tool surface12721273```bash1274# CLI subcommands (npx ruflo metaharness …)1275npx ruflo metaharness score # 5-dim readiness scorecard1276npx ruflo metaharness genome # 7-section categorical report1277npx ruflo metaharness mcp-scan --fail-on high # static security findings1278npx ruflo metaharness threat-model # enterprise threat report1279npx ruflo metaharness oia-audit --alert-on-worst high1280 # composite weekly audit → memory1281npx ruflo metaharness audit-list --since 30d # enumerate audit records1282npx ruflo metaharness audit-trend \ # diff two audits (drift)1283 --baseline-key <a> --current-key <b> --alert-on-worsening \1284 --alert-on-distance-below 0.85 # iter 38 — structural-distance gate (ADR-152 §3.1)1285npx ruflo metaharness similarity \ # iter 36 — ADR-152 §3.1 weighted similarity1286 --a a.json --b b.json [--per-dimension] [--alert-below 0.5]1287npx ruflo metaharness drift-from-history \ # iter 53 — 1-command drift (composes 3 primitives)1288 [--baseline-since 7d] [--baseline-key <key>] [--baseline-file <path>] \1289 [--threshold 0.95] [--alert-on-new-severity high] [--dry-run]1290 # iter 66 — --baseline-key skips audit-list (~14x faster)1291 # iter 67 — --baseline-file skips memory entirely (~19x faster)1292 # iter 78 — --alert-on-new-severity adds orthogonal finding-severity gate1293npx ruflo metaharness mint --name foo --template vertical:coding --confirm1294npx ruflo metaharness redblue init # @metaharness/redblue — scaffold redblue.yaml1295npx ruflo metaharness redblue run --mock-judge --tests 101296 # $0 marker-fixture path (CI / offline)1297npx ruflo metaharness redblue run --tests 50 --patch1298 # real model judge (needs OPENROUTER_API_KEY,1299 # capped by max_cost_usd, default $3)1300npx ruflo metaharness redblue attack prompt --count 31301 # preview generated attack cases (no target call)1302npx ruflo metaharness redblue patch --mock-judge # baseline → blue-team patch → retest delta1303npx ruflo metaharness redblue report --in report.json1304 # render existing report as markdown1305npx ruflo metaharness learn --host claude-code --model haiku --slice slices/lite.json1306 # metaharness@0.3.0 / upstream ADR-235 —1307 # GEPA learning run; $0 dry-run default,1308 # --run to spend; needs a metaharness1309 # repo checkout (--repo / $METAHARNESS_REPO)1310npx ruflo metaharness gepa --op genome # darwin@0.8.0 GEPA library — load + validate1311 # the shipped cand-6 genome (or --path <f>)1312npx ruflo metaharness gepa --op render # genome → the system prompt it compiles to1313npx ruflo metaharness gepa --op analyze --transcript run.json1314 # classify failure modes in a transcript1315npx ruflo metaharness evolve --bench .harness/bench.json1316 # Darwin proposes candidates; governed gates decide1317npx ruflo metaharness bench verify --path .harness/bench.json1318 # create or verify stable benchmark corpora1319npx ruflo metaharness flywheel run --proposer auto --max-concurrency 21320 # bounded concurrent evaluation; does not promote1321npx ruflo metaharness flywheel receipts # inspect immutable evaluation receipts1322npx ruflo metaharness flywheel promote <receipt-id> \1323 --public-key ./approved-ed25519-public.pem --confirm1324 # explicit policy-authorized atomic promotion13251326# Dedicated command1327npx ruflo eject --name my-harness # lift ruflo project → standalone harness1328 # dry-run by default; refuses in-repo target13291330# Doctor health check1331npx ruflo doctor --component metaharness # report metaharness availability + version13321333# MCP tools (callable by Claude Code agents)1334mcp__claude-flow__metaharness_score1335mcp__claude-flow__metaharness_genome1336mcp__claude-flow__metaharness_mcp_scan1337mcp__claude-flow__metaharness_threat_model1338mcp__claude-flow__metaharness_oia_audit1339mcp__claude-flow__metaharness_audit_list1340mcp__claude-flow__metaharness_audit_trend1341mcp__claude-flow__metaharness_similarity # iter 36 — ADR-152 §3.1 genome similarity1342mcp__claude-flow__metaharness_drift_from_history # iter 53 — 1-command drift detection1343mcp__claude-flow__metaharness_bench # ADR-153 — create/verify bench suites for evolve --bench1344mcp__claude-flow__metaharness_evolve # MAP-Elites driver — evolve a harness across bench suites1345mcp__claude-flow__metaharness_security_bench # security-focused benchmark suite gate1346mcp__claude-flow__metaharness_redblue # @metaharness/redblue — adversarial red/blue LLM testing (init|run|patch|attack|report)1347mcp__claude-flow__metaharness_learn # metaharness@0.3.0 — GEPA learning run ($0 dry-run default; run=true to spend)1348mcp__claude-flow__metaharness_gepa # darwin@0.8.0 — GEPA genome ops (genome|validate|render|analyze); gepaOptimize stays library-only1349mcp__claude-flow__metaharness_flywheel # ADR-322 — evaluate concurrently, inspect receipts/ledger, or explicitly promote1350```13511352### Routing integration (ADR-148/149)13531354`@metaharness/router@~0.3.2` is wired as the cost-optimal model router behind the `CLAUDE_FLOW_ROUTER_NEURAL=1` triple-gate. The `routedBy` field on every routing decision carries `'metaharness-knn' | 'metaharness-krr' | 'fastgrnn'` when the neural path is active.13551356### SelfEvolvingRouter parallel-logging (ADR-150 Phase 2)13571358When `CLAUDE_FLOW_ROUTER_PARALLEL_LOG=1` is set, every `route()` call writes a paired-decision row (bandit pick + neural-augmented pick + outcome) to `.swarm/router-parallel.jsonl`. Analyze with:13591360```bash1361node plugins/ruflo-metaharness/scripts/router-parallel-analyze.mjs \1362 --input .swarm/router-parallel.jsonl --strict1363```13641365The 3-criteria AND-gate from ADR-150 review-round-1: `quality > 2% AND cost < 1% AND latency < 5%`. Exit 1 in `--strict` mode if any criterion fails — promotion gate.13661367### CI workflows13681369- `metaharness-ci.yml` — score / mcp-scan / router-compat / eject-dryrun jobs on every PR touching `plugins/ruflo-metaharness/**`1370- `no-metaharness-smoke.yml` — enforces the four architectural-constraint rules above on every PR1371- `oia-audit-weekly.yml` — Sundays 04:17 UTC, runs composite audit, uploads 90-day artifact13721373### Cross-references13741375- [ADR-150](v3/docs/adr/ADR-150-metaharness-integration-surfaces.md) — decision + implementation notes1376- [Issue #2399](https://github.com/ruvnet/ruflo/issues/2399) — phase tracker1377- [Research gist](https://gist.github.com/ruvnet/19d166ff9acf368c9da4172d91ac9113) — graded evidence1378- Upstream: `github.com/ruvnet/agent-harness-generator`13791380## Optional Plugins (20 Available)13811382Plugins are distributed via IPFS and can be installed with the CLI. Browse and install from the official registry:13831384```bash1385# List all available plugins1386npx claude-flow@v3alpha plugins list13871388# Install a plugin1389npx claude-flow@v3alpha plugins install @claude-flow/plugin-name13901391# Enable/disable1392npx claude-flow@v3alpha plugins enable @claude-flow/plugin-name1393npx claude-flow@v3alpha plugins disable @claude-flow/plugin-name1394```13951396### Core Plugins13971398| Plugin | Version | Description |1399|--------|---------|-------------|1400| `@claude-flow/embeddings` | 3.0.0-alpha.1 | Vector embeddings with sql.js, HNSW, hyperbolic support |1401| `@claude-flow/security` | 3.0.0-alpha.1 | Input validation, path security, CVE remediation |1402| `@claude-flow/claims` | 3.0.0-alpha.8 | Claims-based authorization (check, grant, revoke, list) |1403| `@claude-flow/neural` | 3.0.0-alpha.7 | Neural pattern training (SONA, MoE, EWC++) |1404| `@claude-flow/plugins` | 3.0.0-alpha.1 | Plugin system core (manager, discovery, store) |1405| `@claude-flow/performance` | 3.0.0-alpha.1 | Performance profiling and benchmarking |14061407### Integration Plugins14081409| Plugin | Version | Description |1410|--------|---------|-------------|1411| `@claude-flow/plugin-agentic-qe` | 3.0.0-alpha.4 | Agentic quality engineering integration |1412| `@claude-flow/plugin-prime-radiant` | 0.1.5 | Prime Radiant intelligence integration |1413| `@claude-flow/plugin-gastown-bridge` | 3.0.0-alpha.1 | Gastown bridge protocol integration |1414| `@claude-flow/teammate-plugin` | 1.0.0-alpha.1 | Multi-agent teammate coordination |1415| `@claude-flow/plugin-code-intelligence` | 0.1.0 | Advanced code analysis and intelligence |1416| `@claude-flow/plugin-test-intelligence` | 0.1.0 | Intelligent test generation and gap analysis |1417| `@claude-flow/plugin-perf-optimizer` | 0.1.0 | Performance optimization automation |1418| `@claude-flow/plugin-neural-coordinator` | 0.1.0 | Neural network coordination across agents |1419| `@claude-flow/plugin-cognitive-kernel` | 0.1.0 | Core cognitive processing kernel |1420| `@claude-flow/plugin-quantum-optimizer` | 0.1.0 | Quantum-inspired optimization algorithms |1421| `@claude-flow/plugin-hyperbolic-reasoning` | 0.1.0 | Hyperbolic space reasoning for hierarchical data |14221423### Domain-Specific Plugins14241425| Plugin | Version | Description |1426|--------|---------|-------------|1427| `@claude-flow/plugin-healthcare-clinical` | 0.1.0 | Healthcare clinical workflow automation |1428| `@claude-flow/plugin-financial-risk` | 0.1.0 | Financial risk assessment and modeling |1429| `@claude-flow/plugin-legal-contracts` | 0.1.0 | Legal contract analysis and generation |14301431### Plugin Development14321433```bash1434# Create a new plugin from template1435npx claude-flow@v3alpha plugins create my-plugin14361437# Test locally1438npx claude-flow@v3alpha plugins install ./path/to/my-plugin14391440# Publish to registry (requires Pinata credentials)1441npx claude-flow@v3alpha plugins publish1442```14431444Registry source: IPFS via Pinata (`QmXbfEAaR7D2Ujm4GAkbwcGZQMHqAMpwDoje4583uNP834`)14451446## Support14471448- Documentation: https://github.com/ruvnet/claude-flow1449- Issues: https://github.com/ruvnet/claude-flow/issues14501451---14521453Remember: **Claude Flow coordinates, Claude Code creates!**14541455## Gateway-Delegated Development (meta-llm dev-bridge)14561457For complex reasoning, architecture decisions, or hard bug-fixes, **delegate via the1458`metallm_delegate` MCP tool rather than solving inline.** The meta-llm gateway governs the1459work: it routes cheap-tier-first, escalates genuinely-hard tasks to the frontier (Fable),1460and meters every call — so delegation is cost-governed and preserves the main session's context.14611462- **Default to `cognitum-auto`** — the gateway picks the tier by difficulty. Only pass an1463 explicit tier (`cognitum-low|mid|high`) when you must force one.1464- Prompt-wrapping does **not** inflate cost — the gateway normalizes host scaffolds so an1465 everyday sub-task still routes to the cheap tier. Trust `cognitum-auto`.1466- Use **`metallm_delegate`** for agentic sub-tasks needing tools/files in a working dir1467 (its `cwd` is sandboxed); use **`metallm_ask`** for a single-shot question — it returns1468 the gateway's real metered cost + resolved tier/model in-band.1469- Reserve the main (inline) session for orchestration, integration, and final review;1470 push expensive per-sub-task reasoning through the gateway.14711472**Setup (per developer, local — never committed):** register the `metallm-dev-bridge` MCP1473server via a local `.mcp.json` (gitignored) and export your gateway key as `COGNITUM_DEV_KEY`1474in your shell. Build steps + the exact `.mcp.json` block are in the internal meta-llm1475dev-bridge README. **Never commit the key or an inline gateway URL.**14761477### `ask` vs `delegate` — pick by task shape (load-bearing)14781479**Use `metallm_ask` for single-shot facts, summaries, classification, and small code1480questions. Use `metallm_delegate` only when the task needs autonomous multi-step execution1481or isolated agent context.**14821483Why the split is strict: `metallm_delegate` spawns a full `claude -p` sub-agent, which loads1484its entire harness context **even for a trivial task** — measured floor ≈ **$0.26/call**1485(~43k input tokens) before any real work. `metallm_ask` is a single gateway completion —1486measured ≈ **$0.0001** for a small query, ~2500× cheaper. So delegating casually is1487expensive at volume; `delegate` pays off only when offloading the sub-task's context from1488the main session is worth the floor. When in doubt, `ask`.14891490Routing caveat (tracked): `metallm_ask` **auto** currently over-tiers some trivial prompts to1491`mid` (sonnet-5) instead of `low` — the bridge's `/v1/messages` path may miss ADR-2361492host-normalization (meta-llm issue #38). Forced tiers work correctly; cost impact is small1493per call but real at volume.1494
Also in ruvnet/ruflo
Diff this repo’s formatsOne repository carrying more than one format is the comparison this product exists for: does anyone actually write different content in each file, or is one a copy of the other?
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| ruvnet/rufloAGENTS.md · 67k | AGENTS.md | buildteststyletypes+5 | 81/100 | 3 days ago | |
| ruvnet/rufloruflo/src/ruvocal/CLAUDE.md · 67k | CLAUDE.md | setupbuildtestlint-format+6 | 97/100 | 3 days ago | |
| ruvnet/ruflov3/@claude-flow/cli/CLAUDE.md · 67k | CLAUDE.md | teststyletypestesting-strategy+4 | 69/100 | 3 days ago | |
| ruvnet/ruflov3/@claude-flow/codex/AGENTS.md · 67k | AGENTS.md | setupbuildteststyle+8 | 96/100 | 3 days ago | |
| ruvnet/ruflov3/@claude-flow/mcp/CLAUDE.md · 67k | CLAUDE.md | teststyletypestesting-strategy+4 | 69/100 | 3 days ago | |
| ruvnet/ruflov3/CLAUDE.md · 67k | CLAUDE.md | setupbuildtestarch+4 | 70/100 | 3 days ago |
Similar configs
Same format, overlapping stack, ranked by quality.
| Repository | Format | Stack | Covers | Score | Changed |
|---|---|---|---|---|---|
| Adit-Jain-srm/NightmareNetCLAUDE.md · 45 | CLAUDE.md | buildtestlint-formatstyle+6 | 100/100 | 3 days ago | |
| bagisto/bagistoCLAUDE.md · 28k | CLAUDE.md | setupbuildteststyle+5 | 100/100 | 3 days ago | |
| microsoft/playwrightCLAUDE.md · 94k | CLAUDE.md | buildtestlint-formatstyle+7 | 100/100 | 3 days ago | |
| dotCMS/corecore-web/CLAUDE.md · 949 | CLAUDE.md | teststylearchtesting-strategy+3 | 100/100 | 3 days ago | |
| nimbalyst/nimbalystpackages/android/CLAUDE.md · 1.4k | CLAUDE.md | setupbuildstylearch+2 | 100/100 | 3 days ago | |
| filamentphp/filamentCLAUDE.md · 32k | CLAUDE.md | buildtestlint-formatstyle+7 | 100/100 | 3 days ago | |
| dotCMS/coreCLAUDE.md · 949 | CLAUDE.md | setupbuildteststyle+7 | 99/100 | today | |
| lollipopkit/flutter_server_boxCLAUDE.md · 8.3k | CLAUDE.md | buildteststylearch+2 | 98/100 | 3 days ago |
