{"owner":"ruvnet","repo":"ruflo","hasSkills":true,"hasMcp":false,"mcpConfig":null,"found":["CLAUDE.md","AGENTS.md"],"skills":{"CLAUDE.md":"# Claude Code Configuration - Ruflo V3\n\n> Public release train: `@claude-flow/cli`, `claude-flow`, and `ruflo`.\n> Use package manifests and the registry as version truth; do not copy stale\n> version or capability counts into agent guidance.\n\n## Behavioral Rules (Always Enforced)\n\n- Do what has been asked; nothing more, nothing less\n- NEVER create files unless they're absolutely necessary for achieving your goal\n- ALWAYS prefer editing an existing file to creating a new one\n- NEVER proactively create documentation files (*.md) or README files unless explicitly requested\n- NEVER save working files, text/mds, or tests to the root folder\n- Never continuously check status after spawning a swarm — wait for results\n- ALWAYS read a file before editing it\n- NEVER commit secrets, credentials, or .env files\n\n## Capability Brain and Governed Implementation\n\nRuflo is the coordination ledger and policy decision point. Claude Code\nexecutes code, tests, commands, and file changes. A Ruflo coordination call\nrecords work; it does not perform the implementation.\n\nWhen registered, call\n`guidance_brain({ mode: \"recommend\", task: \"...\" })` before complex Ruflo\nwork. Use its live registry rather than guessing tool names. Treat\n`registered`, `configured`, `reachable`, `healthy`, and `authorized` as\nseparate facts. If unavailable, continue with compatible guidance tools, CLI\ndiscovery, and these repository instructions.\n\nUse this loop: recall → inspect → route → plan → execute → test → validate →\nbenchmark → optimize → receipt → handoff → separately authorized publish.\n\n## File Organization\n\n- NEVER save to root folder — use the directories below\n- Use `/src` for source code files\n- Use `/tests` for test files\n- Use `/docs` for documentation and markdown files\n- Use `/config` for configuration files\n- Use `/scripts` for utility scripts\n- Use `/examples` for example code\n\n## Project Architecture\n\n- Follow Domain-Driven Design with bounded contexts\n- Keep files under 500 lines\n- Use typed interfaces for all public APIs\n- Prefer TDD London School (mock-first) for new code\n- Use event sourcing for state changes\n- Ensure input validation at system boundaries\n\n### Key Packages\n\n| Package | Path | Purpose |\n|---------|------|---------|\n| `@claude-flow/cli` | `v3/@claude-flow/cli/` | CLI entry point (26 commands) |\n| `@claude-flow/codex` | `v3/@claude-flow/codex/` | Dual-mode Claude + Codex collaboration |\n| `@claude-flow/guidance` | `v3/@claude-flow/guidance/` | Governance control plane |\n| `@claude-flow/hooks` | `v3/@claude-flow/hooks/` | 17 hooks + 12 workers |\n| `@claude-flow/memory` | `v3/@claude-flow/memory/` | AgentDB + HNSW search |\n| `@claude-flow/security` | `v3/@claude-flow/security/` | Input validation, CVE remediation |\n\n## Concurrent Automated Development\n\n- Parallelize independent research, tests, reviews, and non-overlapping\n  implementation.\n- Never allow two writers in one worktree. Give every writing agent an isolated\n  worktree and explicit file ownership.\n- Read-only agents may share a checkout; writing agents may not.\n- Only the integration owner edits shared manifests and lockfiles or reconciles\n  overlapping changes.\n- Continue independent local work after spawning agents; wait only when a real\n  dependency blocks progress. Do not repeatedly poll.\n- A lease or work claim coordinates ownership; it never grants authority.\n- Bind tests, benchmarks, policy decisions, and handoffs to an exact clean\n  commit or immutable dirty-worktree snapshot.\n- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose and\n  evaluate candidates, but cannot self-promote or expand tools, network,\n  secrets, spend, concurrency, or release authority.\n\n---\n\n## Swarm Orchestration\n\n- MUST initialize the swarm using MCP tools when starting complex tasks\n- MUST spawn concurrent agents using Claude Code's Task tool\n- Never use MCP tools alone for execution — Task tool agents do the actual work\n\n### MCP + Task Tool in SAME Message\n\n- MUST call MCP tools AND Task tool in ONE message for complex work\n- Always call MCP first, then IMMEDIATELY call Task tool to spawn agents\n\n### 3-Tier Model Routing (ADR-026, ADR-143)\n\n| Tier | Handler | Latency | Cost | Use Cases |\n|------|---------|---------|------|-----------|\n| **1** | Deterministic codemod | ~1ms | $0 | Structural transforms with **no LLM**: `var-to-const`, `remove-console`, `add-logging` |\n| **2** | Haiku | ~500ms | $0.0002 | Simple tasks, low complexity (<30%) |\n| **3** | Sonnet/Opus | 2-5s | $0.003-0.015 | Complex reasoning, architecture, security (>30%) |\n\n- Always check for `[CODEMOD_AVAILABLE]` or `[TASK_MODEL_RECOMMENDATION]` before spawning agents\n- 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`\n- `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)\n- 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 path\n\n## Swarm Configuration & Anti-Drift\n\n### Anti-Drift Coding Swarm (PREFERRED DEFAULT)\n\n- ALWAYS use hierarchical topology for coding swarms\n- Keep maxAgents at 6-8 for tight coordination\n- Use specialized strategy for clear role boundaries\n- Use `raft` consensus for hive-mind (leader maintains authoritative state)\n- Run frequent checkpoints via `post-task` hooks\n- Keep shared memory namespace for all agents\n- Keep task cycles short with verification gates\n\n```javascript\nmcp__ruv-swarm__swarm_init({\n  topology: \"hierarchical\",\n  maxAgents: 8,\n  strategy: \"specialized\"\n})\n```\n\n## Dual-Mode Collaboration (Claude Code + Codex)\n\nThis 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.\n\n### Why Dual-Mode?\n\n| Single Platform | Dual-Mode Collaboration |\n|----------------|------------------------|\n| One model's perspective | Two AI platforms cross-validating |\n| Limited reasoning styles | Complementary strengths |\n| No external verification | Built-in code review |\n| Sequential workflows | Parallel execution |\n\n### Dual-Mode Swarm Protocol\n\nFor complex tasks, spawn both Claude and Codex workers in parallel:\n\n```javascript\n// STEP 1: Initialize dual-mode swarm\nmcp__ruv-swarm__swarm_init({\n  topology: \"hierarchical\",\n  maxAgents: 8,\n  strategy: \"specialized\"\n})\n\n// STEP 2: Spawn BOTH platforms in parallel via Task tool\n// 🔵 Claude Code workers (architecture, security, testing)\nTask(\"Architect\", \"Design the implementation. Store design in memory namespace 'collaboration'.\", \"system-architect\")\nTask(\"Tester\", \"Write tests based on architect's design. Read from 'collaboration' namespace.\", \"tester\")\nTask(\"Reviewer\", \"Review code quality and security. Store findings in 'collaboration'.\", \"reviewer\")\n\n// 🟢 Codex workers (implementation, optimization)\n// Spawn via CLI for Codex platform\nBash(\"npx claude-flow-codex dual run --worker 'codex:coder:Implement the solution based on architect design' --namespace collaboration\")\nBash(\"npx claude-flow-codex dual run --worker 'codex:optimizer:Optimize performance based on implementation' --namespace collaboration\")\n\n// STEP 3: Coordinate via shared memory\nBash(\"npx claude-flow@v3alpha memory store --namespace collaboration --key 'task-context' --value '[task description]'\")\n```\n\n### Collaboration Templates (Pre-Built Pipelines)\n\n| Template | Workers | Pipeline |\n|----------|---------|----------|\n| `feature` | 🔵 Architect → 🟢 Coder → 🔵 Tester → 🟢 Reviewer | Full feature development |\n| `security` | 🔵 Analyst → 🟢 Scanner → 🔵 Reporter | Security audit workflow |\n| `refactor` | 🔵 Architect → 🟢 Refactorer → 🔵 Tester | Code modernization |\n| `bugfix` | 🔵 Researcher → 🟢 Coder → 🔵 Tester | Bug investigation & fix |\n\n### Dual-Mode CLI Commands\n\n```bash\n# Run a collaboration template\nnpx claude-flow-codex dual run feature --task \"Add user authentication with OAuth\"\nnpx claude-flow-codex dual run security --target \"./src\"\nnpx claude-flow-codex dual run refactor --target \"./src/legacy\"\n\n# Custom multi-platform swarm\nnpx claude-flow-codex dual run \\\n  --worker \"claude:architect:Design the API structure\" \\\n  --worker \"codex:coder:Implement REST endpoints\" \\\n  --worker \"claude:tester:Write integration tests\" \\\n  --worker \"codex:reviewer:Review code quality\" \\\n  --namespace \"api-feature\"\n\n# Check collaboration status\nnpx claude-flow-codex dual status\n\n# List available templates\nnpx claude-flow-codex dual templates\n```\n\n### Shared Memory Coordination\n\nAll workers share state via the `collaboration` namespace:\n\n```bash\n# Store context for cross-platform sharing\nnpx claude-flow@v3alpha memory store --namespace collaboration --key \"design-decisions\" --value \"...\"\n\n# Search for patterns across all workers\nnpx claude-flow@v3alpha memory search --namespace collaboration --query \"authentication patterns\"\n\n# Retrieve specific findings\nnpx claude-flow@v3alpha memory retrieve --namespace collaboration --key \"security-findings\"\n```\n\n### Cross-Platform Learning\n\nBoth platforms learn from each other's outputs:\n\n```bash\n# After successful collaboration, train patterns\nnpx claude-flow@v3alpha hooks post-task --task-id \"dual-[id]\" --success true --train-neural true\n\n# Store successful collaboration patterns\nnpx claude-flow@v3alpha memory store --namespace patterns --key \"dual-mode-[pattern]\" --value \"[what worked]\"\n\n# Transfer learnings to both platforms\nnpx claude-flow@v3alpha hooks transfer store --pattern \"dual-collab-success\"\n```\n\n### Worker Dependency Levels\n\nWorkers execute in dependency order:\n\n```\nLevel 0: [🔵 Architect]           # No dependencies - runs first\nLevel 1: [🟢 Coder, 🔵 Tester]    # Depends on Architect\nLevel 2: [🔵 Reviewer]            # Depends on Coder + Tester\nLevel 3: [🟢 Optimizer]           # Depends on Reviewer approval\n```\n\n### Platform Strengths\n\n| Task Type | Preferred Platform | Reason |\n|-----------|-------------------|--------|\n| Architecture & Design | 🔵 Claude | Strong reasoning, system thinking |\n| Implementation | 🟢 Codex | Fast code generation |\n| Security Review | 🔵 Claude | Careful analysis, threat modeling |\n| Performance Optimization | 🟢 Codex | Code-level optimizations |\n| Testing Strategy | 🔵 Claude | Coverage analysis, edge cases |\n| Refactoring | 🟢 Codex | Bulk code transformations |\n\n### Programmatic API\n\n```typescript\nimport { DualModeOrchestrator, CollaborationTemplates } from '@claude-flow/codex';\n\nconst orchestrator = new DualModeOrchestrator({\n  namespace: 'my-feature',\n  memoryBackend: 'hybrid'\n});\n\n// Use pre-built template\nconst workers = CollaborationTemplates.featureDevelopment('Add OAuth login');\n\n// Run collaboration\nconst results = await orchestrator.runCollaboration(workers, 'Implement OAuth feature');\n\n// Access shared memory\nconst designDocs = await orchestrator.getMemory('design-decisions');\n```\n\n---\n\n## Swarm Protocols & Routing\n\n### Auto-Start Swarm Protocol\n\nWhen the user requests a complex task (multi-file changes, feature implementation, refactoring), **immediately execute this pattern in a SINGLE message:**\n\n```javascript\n// STEP 1: Initialize swarm coordination via MCP\nmcp__ruv-swarm__swarm_init({\n  topology: \"hierarchical\",\n  maxAgents: 8,\n  strategy: \"specialized\"\n})\n\n// STEP 2: Spawn NAMED agents concurrently — all in ONE message\n// Each agent knows WHO to message next in the pipeline\nTask({\n  prompt: \"Research requirements and codebase. SendMessage findings to 'architect' when done.\",\n  subagent_type: \"researcher\", name: \"researcher\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for research from 'researcher'. Design implementation. SendMessage design to 'coder'.\",\n  subagent_type: \"system-architect\", name: \"architect\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for design from 'architect'. Implement the solution. SendMessage code paths to 'tester'.\",\n  subagent_type: \"coder\", name: \"coder\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for implementation from 'coder'. Write tests. SendMessage results to 'reviewer'.\",\n  subagent_type: \"tester\", name: \"tester\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for test results from 'tester'. Review code quality and security. Report findings.\",\n  subagent_type: \"reviewer\", name: \"reviewer\", run_in_background: true\n})\n\n// STEP 3: Kick off the pipeline\nSendMessage({ to: \"researcher\", summary: \"Start research\", message: \"[task description and context]\" })\n\n// STEP 4: Batch todos\nTodoWrite({ todos: [\n  {content: \"Research and analyze requirements\", status: \"in_progress\", activeForm: \"Researching\"},\n  {content: \"Design architecture\", status: \"pending\", activeForm: \"Designing\"},\n  {content: \"Implement solution\", status: \"pending\", activeForm: \"Implementing\"},\n  {content: \"Write tests\", status: \"pending\", activeForm: \"Testing\"},\n  {content: \"Review and finalize\", status: \"pending\", activeForm: \"Reviewing\"}\n]})\n\n// Pipeline flow via SendMessage:\n// researcher ──→ architect ──→ coder ──→ tester ──→ reviewer\n```\n\n### Agent Routing (Anti-Drift)\n\n| Code | Task | Agents |\n|------|------|--------|\n| 1 | Bug Fix | coordinator, researcher, coder, tester |\n| 3 | Feature | coordinator, architect, coder, tester, reviewer |\n| 5 | Refactor | coordinator, architect, coder, reviewer |\n| 7 | Performance | coordinator, perf-engineer, coder |\n| 9 | Security | coordinator, security-architect, auditor |\n| 11 | Memory | coordinator, memory-specialist, perf-engineer |\n| 13 | Docs | researcher, api-docs |\n\n**Codes 1-11: hierarchical/specialized (anti-drift). Code 13: mesh/balanced**\n\n### Task Complexity Detection\n\n**AUTO-INVOKE SWARM when task involves:**\n- Multiple files (3+)\n- New feature implementation\n- Refactoring across modules\n- API changes with tests\n- Security-related changes\n- Performance optimization\n- Database schema changes\n\n**SKIP SWARM for:**\n- Single file edits\n- Simple bug fixes (1-2 lines)\n- Documentation updates\n- Configuration changes\n- Quick questions/exploration\n\n## Project Configuration\n\nThis project is configured with Claude Flow V3 (Anti-Drift Defaults):\n- **Topology**: hierarchical (prevents drift via central coordination)\n- **Max Agents**: 8 (smaller team = less drift)\n- **Strategy**: specialized (clear roles, no overlap)\n- **Consensus**: raft (leader maintains authoritative state)\n- **Memory Backend**: hybrid (SQLite + AgentDB)\n- **HNSW Indexing**: Enabled (measured ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force; ANN wins above the crossover)\n- **Neural Learning**: Enabled (SONA)\n\n## V3 CLI Commands (26 Commands, 140+ Subcommands)\n\n### Core Commands\n\n| Command | Subcommands | Description |\n|---------|-------------|-------------|\n| `init` | 4 | Project initialization with wizard, presets, skills, hooks |\n| `agent` | 8 | Agent lifecycle (spawn, list, status, stop, metrics, pool, health, logs) |\n| `swarm` | 6 | Multi-agent swarm coordination and orchestration |\n| `memory` | 11 | AgentDB memory with HNSW vector search (measured ~1.9x–4.7x vs brute force above crossover) |\n| `mcp` | 9 | MCP server management and tool execution |\n| `task` | 6 | Task creation, assignment, and lifecycle |\n| `session` | 7 | Session state management and persistence |\n| `config` | 7 | Configuration management and provider setup |\n| `status` | 3 | System status monitoring with watch mode |\n| `start` | 3 | Service startup and quick launch |\n| `workflow` | 6 | Workflow execution and template management |\n| `hooks` | 17 | Self-learning hooks + 12 background workers |\n| `hive-mind` | 6 | Queen-led Byzantine fault-tolerant consensus |\n\n### Advanced Commands\n\n| Command | Subcommands | Description |\n|---------|-------------|-------------|\n| `daemon` | 5 | Background worker daemon (start, stop, status, trigger, enable) |\n| `neural` | 5 | Neural pattern training (train, status, patterns, predict, optimize) |\n| `security` | 6 | Security scanning (scan, audit, cve, threats, validate, report) |\n| `performance` | 5 | Performance profiling (benchmark, profile, metrics, optimize, report) |\n| `providers` | 5 | AI providers (list, add, remove, test, configure) |\n| `plugins` | 5 | Plugin management (list, install, uninstall, enable, disable) |\n| `deployment` | 5 | Deployment management (deploy, rollback, status, environments, release) |\n| `embeddings` | 4 | Vector embeddings (embed, batch, search, init) — agentic-flow ONNX backend (speedup unverified, no benchmark) |\n| `claims` | 4 | Claims-based authorization (check, grant, revoke, list) |\n| `migrate` | 5 | V2 to V3 migration with rollback support |\n| `process` | 4 | Background process management |\n| `doctor` | 1 | System diagnostics with health checks |\n| `completions` | 4 | Shell completions (bash, zsh, fish, powershell) |\n\n### Quick CLI Examples\n\n```bash\n# Initialize project\nnpx claude-flow@v3alpha init --wizard\n\n# Start daemon with background workers\nnpx claude-flow@v3alpha daemon start\n\n# Spawn an agent\nnpx claude-flow@v3alpha agent spawn -t coder --name my-coder\n\n# Initialize swarm\nnpx claude-flow@v3alpha swarm init --v3-mode\n\n# Search memory (HNSW-indexed)\nnpx claude-flow@v3alpha memory search -q \"authentication patterns\"\n\n# System diagnostics\nnpx claude-flow@v3alpha doctor --fix\n\n# Security scan\nnpx claude-flow@v3alpha security scan --depth full\n\n# Performance benchmark\nnpx claude-flow@v3alpha performance benchmark --suite all\n```\n\n## Headless Background Instances (claude -p)\n\nUse `claude -p` (print/pipe mode) to spawn headless Claude instances for parallel background work. These run non-interactively and return results to stdout.\n\n### Basic Usage\n\n```bash\n# Single headless task\nclaude -p \"Analyze the authentication module for security issues\"\n\n# With model selection\nclaude -p --model haiku \"Format this config file\"\nclaude -p --model opus \"Design the database schema for user management\"\n\n# With output format\nclaude -p --output-format json \"List all TODO comments in src/\"\nclaude -p --output-format stream-json \"Refactor the error handling in api.ts\"\n\n# With budget limits\nclaude -p --max-budget-usd 0.50 \"Run comprehensive security audit\"\n\n# With specific tools allowed\nclaude -p --allowedTools \"Read,Grep,Glob\" \"Find all files that import the auth module\"\n\n# Skip permissions (sandboxed environments only)\nclaude -p --dangerously-skip-permissions \"Fix all lint errors in src/\"\n```\n\n### Parallel Background Execution\n\n```bash\n# Spawn multiple headless instances in parallel\nclaude -p \"Analyze src/auth/ for vulnerabilities\" &\nclaude -p \"Write tests for src/api/endpoints.ts\" &\nclaude -p \"Review src/models/ for performance issues\" &\nwait  # Wait for all to complete\n\n# With results captured\nSECURITY=$(claude -p \"Security audit of auth module\" &)\nTESTS=$(claude -p \"Generate test coverage report\" &)\nPERF=$(claude -p \"Profile memory usage in workers\" &)\nwait\necho \"$SECURITY\" \"$TESTS\" \"$PERF\"\n```\n\n### Session Continuation\n\n```bash\n# Start a task, resume later\nclaude -p --session-id \"abc-123\" \"Start analyzing the codebase\"\nclaude -p --resume \"abc-123\" \"Continue with the test files\"\n\n# Fork a session for parallel exploration\nclaude -p --resume \"abc-123\" --fork-session \"Try approach A: event sourcing\"\nclaude -p --resume \"abc-123\" --fork-session \"Try approach B: CQRS pattern\"\n```\n\n### Key Flags\n\n| Flag | Purpose |\n|------|---------|\n| `-p, --print` | Non-interactive mode, print and exit |\n| `--model <model>` | Select model (haiku, sonnet, opus) |\n| `--output-format <fmt>` | Output: text, json, stream-json |\n| `--max-budget-usd <amt>` | Spending cap per invocation |\n| `--allowedTools <tools>` | Restrict available tools |\n| `--append-system-prompt` | Add custom instructions |\n| `--resume <id>` | Continue a previous session |\n| `--fork-session` | Branch from resumed session |\n| `--fallback-model <model>` | Auto-fallback if primary overloaded |\n| `--permission-mode <mode>` | acceptEdits, bypassPermissions, plan, etc. |\n| `--mcp-config <json>` | Load MCP servers from JSON |\n\n## Available Agents (60+ Types)\n\n### Core Development\n`coder`, `reviewer`, `tester`, `planner`, `researcher`\n\n### V3 Specialized Agents\n`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`\n\n### @claude-flow/security Module\nCVE remediation, input validation, path security:\n- `InputValidator` — Zod-based validation at boundaries\n- `PathValidator` — Path traversal prevention\n- `SafeExecutor` — Command injection protection\n- `PasswordHasher` — bcrypt hashing\n- `TokenGenerator` — Secure token generation\n\n### Token Optimizer (Agent Booster)\nIntegrates agentic-flow optimizations for 30-50% token reduction:\n```typescript\nimport { getTokenOptimizer } from '@claude-flow/integration';\nconst optimizer = await getTokenOptimizer();\n\n// Compact context (32% fewer tokens)\nconst ctx = await optimizer.getCompactContext(\"auth patterns\");\n\n// 352x faster edits = fewer retries\nawait optimizer.optimizedEdit(file, old, new, \"typescript\");\n\n// Optimal config (100% success rate)\nconst config = optimizer.getOptimalConfig(agentCount);\n```\n| Feature | Token Savings |\n|---------|---------------|\n| ReasoningBank retrieval | -32% |\n| Agent Booster edits | -15% |\n| Cache (95% hit rate) | -10% |\n| Optimal batch size | -20% |\n\n### Swarm Coordination\n`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`, `collective-intelligence-coordinator`, `swarm-memory-manager`\n\n### Consensus & Distributed\n`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`, `consensus-builder`, `crdt-synchronizer`, `quorum-manager`, `security-manager`\n\n### Performance & Optimization\n`perf-analyzer`, `performance-benchmarker`, `task-orchestrator`, `memory-coordinator`, `smart-agent`\n\n### GitHub & Repository\n`github-modes`, `pr-manager`, `code-review-swarm`, `issue-tracker`, `release-manager`, `workflow-automation`, `project-board-sync`, `repo-architect`, `multi-repo-swarm`\n\n### SPARC Methodology\n`sparc-coord`, `sparc-coder`, `specification`, `pseudocode`, `architecture`, `refinement`\n\n### Specialized Development\n`backend-dev`, `mobile-dev`, `ml-developer`, `cicd-engineer`, `api-docs`, `system-architect`, `code-analyzer`, `base-template-generator`\n\n### Testing & Validation\n`tdd-london-swarm`, `production-validator`\n\n## Agent Teams & Comms System\n\nAgent 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.\n\n### Architecture\n\n```\nTeam Lead (you)\n  ├── SendMessage ←→ architect (named agent)\n  ├── SendMessage ←→ developer (named agent)\n  ├── SendMessage ←→ tester (named agent)\n  └── SendMessage ←→ reviewer (named agent)\n       ↕ agents can message each other by name\n```\n\n### Core Principle: Named Agents + SendMessage\n\nEvery agent MUST have a `name` so it's addressable. Communication happens via `SendMessage`, not polling or shared memory.\n\n```javascript\n// STEP 1: Spawn named agents (all in ONE message, background)\nTask({\n  prompt: \"Design the API. When done, send your design to 'developer' via SendMessage.\",\n  subagent_type: \"system-architect\",\n  name: \"architect\",\n  run_in_background: true\n})\nTask({\n  prompt: \"Wait for architect's design via SendMessage. Then implement it. Send code to 'tester'.\",\n  subagent_type: \"coder\",\n  name: \"developer\",\n  run_in_background: true\n})\nTask({\n  prompt: \"Wait for developer's code via SendMessage. Write tests. Send results to 'reviewer'.\",\n  subagent_type: \"tester\",\n  name: \"tester\",\n  run_in_background: true\n})\n\n// STEP 2: Kick off the pipeline by messaging the first agent\nSendMessage({\n  to: \"architect\",\n  summary: \"Start API design\",\n  message: \"Design a REST API for user management with CRUD endpoints. Send the design to 'developer' when done.\"\n})\n```\n\n### SendMessage Protocol\n\n```javascript\n// Lead → Teammate: assign work\nSendMessage({ to: \"developer\", summary: \"Implement auth\", message: \"Build OAuth2 flow...\" })\n\n// Lead → Teammate: redirect priorities\nSendMessage({ to: \"developer\", summary: \"Prioritize auth\", message: \"Auth endpoint is blocking tester, do it first.\" })\n\n// Lead → Teammate: provide context from another agent's results\nSendMessage({ to: \"tester\", summary: \"Architect output\", message: \"The architect designed these endpoints: [details]. Write tests for them.\" })\n\n// Lead → Teammate: graceful shutdown\nSendMessage({ to: \"developer\", message: { type: \"shutdown_request\" } })\n```\n\n### Coordination Patterns\n\n**Pipeline (A → B → C)** — each agent messages the next when done:\n```\narchitect ──SendMessage──→ developer ──SendMessage──→ tester ──SendMessage──→ reviewer\n```\nTell each agent WHO to message next in their prompt.\n\n**Fan-out / Fan-in** — lead spawns parallel agents, collects results:\n```\n         ┌→ researcher-1 ──→┐\nlead ────┼→ researcher-2 ──→├──→ lead synthesizes\n         └→ researcher-3 ──→┘\n```\nSpawn with `run_in_background: true`. Results arrive as task completions.\n\n**Supervisor / Worker** — lead assigns, workers report back:\n```\nlead ←──SendMessage──→ worker-1\nlead ←──SendMessage──→ worker-2\nlead ←──SendMessage──→ worker-3\n```\nLead sends tasks via SendMessage, workers respond with results.\n\n### Agent Prompt Template (Comms-Aware)\n\nWhen spawning agents that need to coordinate, include comms instructions:\n\n```javascript\nTask({\n  prompt: `You are the architect for this feature team.\n\nYOUR TASK: Design the database schema for user management.\n\nCOMMS PROTOCOL:\n- When your design is ready, send it to \"developer\" via SendMessage\n- If you need clarification, message the team lead (just output text)\n- Include file paths and key decisions in your message\n\nDELIVERABLE: Schema design with entity relationships, indexes, and migration plan.`,\n  subagent_type: \"system-architect\",\n  name: \"architect\",\n  run_in_background: true\n})\n```\n\n### Full Team Spawn Example\n\n```javascript\n// Create shared task list first\nTaskCreate({ subject: \"Design schema\", description: \"...\", activeForm: \"Designing\" })\nTaskCreate({ subject: \"Implement models\", description: \"...\", activeForm: \"Implementing\" })\nTaskCreate({ subject: \"Write tests\", description: \"...\", activeForm: \"Testing\" })\nTaskCreate({ subject: \"Security review\", description: \"...\", activeForm: \"Reviewing\" })\n\n// Spawn ALL named agents in ONE message\nTask({\n  prompt: \"Design the schema. SendMessage to 'developer' with your design when done. Update task #1.\",\n  subagent_type: \"system-architect\", name: \"architect\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for schema from 'architect'. Implement models + endpoints. SendMessage to 'tester'. Update task #2.\",\n  subagent_type: \"coder\", name: \"developer\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for code from 'developer'. Write integration tests. SendMessage results to 'security'. Update task #3.\",\n  subagent_type: \"tester\", name: \"tester\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for test results from 'tester'. Review for vulnerabilities. Update task #4.\",\n  subagent_type: \"security-auditor\", name: \"security\", run_in_background: true\n})\n```\n\n### Agent Teams Hooks\n\n| Hook | Trigger | Purpose |\n|------|---------|---------|\n| `TeammateIdle` | Teammate finishes turn | Auto-assign pending tasks via SendMessage |\n| `TaskCompleted` | Task marked complete | Train patterns, notify lead via SendMessage |\n\n```bash\nnpx claude-flow@v3alpha hooks teammate-idle --auto-assign true\nnpx claude-flow@v3alpha hooks task-completed -i task-123 --train-patterns true\n```\n\n### Rules\n\n1. **Always name agents** — use `name: \"role-name\"` so they're addressable\n2. **Comms over memory** — use SendMessage for real-time coordination, memory for persistence\n3. **Pipeline prompts** — tell each agent WHO to message next and WHAT to send\n4. **Spawn all at once** — all Task calls in ONE message with `run_in_background: true`\n5. **Don't poll** — agents message back when done; wait for task completion notifications\n6. **Graceful shutdown** — send `{ type: \"shutdown_request\" }` before TeamDelete\n7. **Lead synthesizes** — when agents complete, review ALL results before responding to user\n\n## V3 Hooks System (17 Hooks + 12 Workers)\n\n### Hook Categories\n\n| Category | Hooks | Purpose |\n|----------|-------|---------|\n| **Core** | `pre-edit`, `post-edit`, `pre-command`, `post-command`, `pre-task`, `post-task` | Tool lifecycle |\n| **Session** | `session-start`, `session-end`, `session-restore`, `notify` | Context management |\n| **Intelligence** | `route`, `explain`, `pretrain`, `build-agents`, `transfer` | Neural learning |\n| **Learning** | `intelligence` (trajectory-start/step/end, pattern-store/search, stats, attention) | Reinforcement |\n| **Agent Teams** | `teammate-idle`, `task-completed` | Multi-agent coordination |\n\n### 12 Background Workers\n\n| Worker | Priority | Description |\n|--------|----------|-------------|\n| `ultralearn` | normal | Deep knowledge acquisition |\n| `optimize` | high | Performance optimization |\n| `consolidate` | low | Memory consolidation |\n| `predict` | normal | Predictive preloading |\n| `audit` | critical | Security analysis |\n| `map` | normal | Codebase mapping |\n| `preload` | low | Resource preloading |\n| `deepdive` | normal | Deep code analysis |\n| `document` | normal | Auto-documentation |\n| `refactor` | normal | Refactoring suggestions |\n| `benchmark` | normal | Performance benchmarking |\n| `testgaps` | normal | Test coverage analysis |\n\n### Essential Hook Commands\n\n```bash\n# Core hooks\nnpx claude-flow@v3alpha hooks pre-task --description \"[task]\"\nnpx claude-flow@v3alpha hooks post-task --task-id \"[id]\" --success true\nnpx claude-flow@v3alpha hooks post-edit --file \"[file]\" --train-patterns\n\n# Session management\nnpx claude-flow@v3alpha hooks session-start --session-id \"[id]\"\nnpx claude-flow@v3alpha hooks session-end --export-metrics true\nnpx claude-flow@v3alpha hooks session-restore --session-id \"[id]\"\n\n# Intelligence routing\nnpx claude-flow@v3alpha hooks route --task \"[task]\"\nnpx claude-flow@v3alpha hooks explain --topic \"[topic]\"\n\n# Neural learning\nnpx claude-flow@v3alpha hooks pretrain --model-type moe --epochs 10\nnpx claude-flow@v3alpha hooks build-agents --agent-types coder,tester\n\n# Background workers\nnpx claude-flow@v3alpha hooks worker list\nnpx claude-flow@v3alpha hooks worker dispatch --trigger audit\nnpx claude-flow@v3alpha hooks worker status\n```\n\n## Intelligence System (RuVector)\n\nV3 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)):\n- **SONA**: Self-Optimizing Neural Architecture (measured 0.0043ms/adapt, target <0.05ms met)\n- **MoE**: Mixture of Experts for specialized routing (gate converges — confidence 0.13→0.88 after rewards)\n- **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)\n- **EWC++**: Elastic Weight Consolidation (prevents forgetting)\n- **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)\n\nThe 4-step intelligence pipeline:\n1. **RETRIEVE** — Fetch relevant patterns via HNSW\n2. **JUDGE** — Evaluate with verdicts (success/failure)\n3. **DISTILL** — Extract key learnings via LoRA\n4. **CONSOLIDATE** — Prevent catastrophic forgetting via EWC++\n\n## Embeddings Package (v3.0.0-alpha.12)\n\nFeatures:\n- **sql.js**: Cross-platform SQLite persistent cache (WASM, no native compilation)\n- **Document chunking**: Configurable overlap and size\n- **Normalization**: L2, L1, min-max, z-score\n- **Hyperbolic embeddings**: Poincare ball model for hierarchical data\n- **agentic-flow ONNX integration**: speedup unverified (no benchmark; backend reported `onnx`, model all-MiniLM-L6-v2, 384-dim)\n- **Neural substrate**: Integration with RuVector\n\n## Hive-Mind Consensus\n\n### Topologies\n- `hierarchical` — Queen controls workers directly\n- `mesh` — Fully connected peer network\n- `hierarchical-mesh` — Hybrid (recommended)\n- `adaptive` — Dynamic based on load\n\n### Consensus Strategies\n- `byzantine` — BFT (tolerates f < n/3 faulty)\n- `raft` — Leader-based (tolerates f < n/2)\n- `gossip` — Epidemic for eventual consistency\n- `crdt` — Conflict-free replicated data types\n- `quorum` — Configurable quorum-based\n\n## V3 Performance Targets\n\n> 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\".\n\n| Metric | Measured / Target | Status |\n|--------|-------------------|--------|\n| 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) |\n| Int8 Quantization | 3.84x compression, reconstruction cosine 0.99999 | **Measured** |\n| RaBitQ Quantization | 32x compression, 0.60ms/query (14,760-vec index) | **Measured** |\n| SONA Adaptation | 0.0043ms/adapt (target <0.05ms met) | **Measured** |\n| MoE Gate | converges — confidence 0.13→0.88, Q 0→99.8 after rewards | **Measured** |\n| 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 |\n| MCP Response | <100ms | target |\n| CLI Startup | <500ms | target |\n\n## Environment Variables\n\n```bash\n# Configuration\nCLAUDE_FLOW_CONFIG=./claude-flow.config.json\nCLAUDE_FLOW_LOG_LEVEL=info\n\n# Provider API Keys\nANTHROPIC_API_KEY=sk-ant-...\nOPENAI_API_KEY=sk-...\nGOOGLE_API_KEY=...\n\n# MCP Server\nCLAUDE_FLOW_MCP_PORT=3000\nCLAUDE_FLOW_MCP_HOST=localhost\nCLAUDE_FLOW_MCP_TRANSPORT=stdio\n\n# Memory\nCLAUDE_FLOW_MEMORY_BACKEND=hybrid\nCLAUDE_FLOW_MEMORY_PATH=./data/memory\n```\n\n## Doctor Health Checks\n\nRun `npx claude-flow@v3alpha doctor` to check:\n- Node.js version (20+)\n- npm version (9+)\n- Git installation\n- Config file validity\n- Daemon status\n- Memory database\n- API keys\n- MCP servers\n- Disk space\n- TypeScript installation\n\n## Quick Setup\n\n```bash\n# Add MCP servers\nclaude mcp add claude-flow -- npx -y ruflo@latest mcp start\nclaude mcp add ruv-swarm npx ruv-swarm mcp start  # Optional\nclaude mcp add flow-nexus npx flow-nexus@latest mcp start  # Optional\n\n# Start daemon\nnpx claude-flow@v3alpha daemon start\n\n# Run doctor\nnpx claude-flow@v3alpha doctor --fix\n```\n\n## Claude Code vs MCP Tools\n\n### Claude Code Handles ALL EXECUTION:\n- **Task tool**: Spawn and run agents concurrently\n- File operations (Read, Write, Edit, MultiEdit, Glob, Grep)\n- Code generation and programming\n- Bash commands and system operations\n- TodoWrite and task management\n- Git operations\n\n### MCP Tools ONLY COORDINATE:\n- Swarm initialization (topology setup)\n- Agent type definitions\n- Task orchestration\n- Memory management\n- Neural features\n- Performance tracking\n\n- Keep MCP for coordination strategy only — use Claude Code's Task tool for real execution\n\n## Claude Code ↔ AgentDB Memory Bridge\n\nClaude Code's auto-memory (`~/.claude/projects/*/memory/*.md`) is bridged to AgentDB with ONNX vector embeddings for semantic search.\n\n### MCP Tools\n\n| Tool | Description |\n|------|-------------|\n| `memory_import_claude` | Import Claude Code memories into AgentDB with 384-dim ONNX embeddings. Use `allProjects: true` to import from ALL projects. |\n| `memory_bridge_status` | Show bridge health — Claude files, AgentDB entries, SONA state, connection status |\n| `memory_search_unified` | Semantic search across ALL namespaces (claude-memories, auto-memory, patterns, tasks, feedback) |\n\n### Auto-Import on Session Start\n\nThe `SessionStart` hook automatically imports current project's memories into AgentDB. For manual import of all projects:\n\n```bash\n# Via MCP tool (from Claude Code)\nmemory_import_claude({ allProjects: true })\n\n# Via helper hook (from terminal)\nnode .claude/helpers/auto-memory-hook.mjs import-all\n```\n\n### Unified Search\n\nSearch across both Claude Code memories and AgentDB entries:\n\n```bash\n# Via MCP tool\nmemory_search_unified({ query: \"authentication security\", limit: 5 })\n\n# Results include source attribution: claude-code, auto-memory, or agentdb\n```\n\n### Intelligence Pipeline\n\n| Component | Status | Details |\n|-----------|--------|---------|\n| ONNX Embeddings | Active | all-MiniLM-L6-v2, 384 dimensions |\n| SONA Learning | Active | Pattern matching + trajectory recording |\n| ReasoningBank | Active | Pattern storage with file persistence |\n| AgentDB sql.js | Active | SQLite with vector_indexes table |\n\n## Publishing to npm\n\n### Versioning policy (stable releases — alpha series ended at 3.7.0-alpha.81, 2026-05-23)\n\n- **From 3.7.0 onward we ship stable semver**, NOT alpha pre-releases.\n- Bump rules (semver discipline):\n  - **PATCH** (3.7.0 → 3.7.1): bug fixes only, no API change, no schema change\n  - **MINOR** (3.7.0 → 3.8.0): backward-compatible additions (new MCP tool, new flag, new agent type)\n  - **MAJOR** (3.x → 4.0.0): breaking change in CLI surface, MCP tool signature, file layout, or default behavior\n- 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`.\n- Never publish a pre-release (`-alpha.N`, `-beta.N`, `-rc.N`) unless the user explicitly asks for a pre-release flow.\n\n### Publishing Rules\n\n- The normal public release train is exactly THREE packages:\n  `@claude-flow/cli`, `claude-flow`, and `ruflo`.\n- Internal `@claude-flow/*` components are bundled into the public artifacts;\n  do not publish them standalone as part of the normal release.\n- MUST update ALL dist-tags for ALL THREE packages after publishing (latest + alpha + v3alpha all point to the same version)\n- Publish order: `@claude-flow/cli` first, then `claude-flow` (umbrella), then `ruflo` (alias umbrella)\n- MUST run verification for ALL THREE before telling user publishing is complete\n- Run `node scripts/audit-umbrella-version-lockstep.mjs` before packing or\n  publishing.\n- Publish from a clean reviewed commit/tag-equivalent worktree. Do not ship\n  unrelated uncommitted changes.\n- A fresh worktree has two separate dependency trees to install before anything\n  builds: `npm install` at repo root (npm workspaces), AND `pnpm install` inside\n  `v3/` (a separate pnpm workspace — root `prepare-root-publish.mjs` shells out to\n  `pnpm --filter` to build `v3/@claude-flow/{shared,hooks,guidance}`, which fails\n  with `spawn ENOENT` on `tsc` if `v3/node_modules` was never populated).\n- Use the existing authenticated `ruvnet` npm session. Do not replace it with a\n  token from another GCP project.\n\n**`npm publish` auth — FIXED (2026-07-30):** use the `NPM_TOKEN` secret directly,\nvia a throwaway `.npmrc` with `NPM_CONFIG_USERCONFIG` — same pattern as the\nhelpers-signing-key handling. It is mirrored in two GCP projects — `ruv-dev`\n(version 3+) and `cognitum-20260110` (version 7+) — so either project's copy\nis current; use whichever `gcloud` session is already authenticated. This is a\ngranular access token (\"ruflo publishjing\", expires 2026-10-28) with\n`package: write` + `bypass_2fa: true`, scoped broadly enough to cover\n`@claude-flow/cli`, `claude-flow`, and `ruflo` (plus the `cognitum`/\n`cognitum-one` orgs). Confirmed end-to-end against the real registry (not just\na permissions probe): `npm publish` for `@claude-flow/cli` succeeded via this\ntoken with zero OTP/WebAuthn prompt, and\n`npm dist-tag add` against both a scoped (`@claude-flow/cli`) and unscoped\n(`claude-flow`) package also went through with no prompt.\n\n**Why the earlier `NPM_TOKEN` version failed:** versions 1/2 of that secret\nwere older classic automation tokens, and npm has been restricting tokens that\nbypass 2FA for writes account-wide (the login flow prints this notice —\n`gh.io/npm-gat-bypass2fa-deprecation`). Version 3 is a **granular access\ntoken** created explicitly for this purpose, which is npm's supported\nreplacement path (its own 2FA-bypass flag still works for a granular token,\nunlike the deprecated classic automation tokens). If this token's `bypass_2fa`\nflag or scope ever gets narrowed/expired (check expiry above), the fallback\nis the WebAuthn dance below — but try this path first every time.\n\n```bash\ngcloud secrets versions access latest --secret=NPM_TOKEN --project=ruv-dev > /tmp/.npmrc-publish-raw\nprintf '//registry.npmjs.org/:_authToken=%s\\n' \"$(cat /tmp/.npmrc-publish-raw)\" > /tmp/.npmrc-publish\nrm -f /tmp/.npmrc-publish-raw\nNPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm publish   # from the package dir, with signing-key env vars for @claude-flow/cli\nNPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> alpha\nNPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> v3alpha\nshred -u /tmp/.npmrc-publish 2>/dev/null || rm -f /tmp/.npmrc-publish   # ALWAYS clean up, same discipline as the signing key\n```\n\n**Fallback — WebAuthn procedure, if the token above is dead:** the `ruvnet`\naccount's 2FA method is a WebAuthn security key, not TOTP (no numeric\n`--otp=<code>` exists). This must be driven by the human (an agent cannot\napprove a WebAuthn browser prompt):\n1. Human goes to npmjs.com → account 2FA settings → turns OFF \"Require\n   two-factor authentication for write actions\" (narrows to auth-only, not a\n   full 2FA disable), then runs `npm login` in their own terminal to refresh\n   the session under the new setting.\n2. Agent can then run `npm publish` directly via Bash with no further prompt.\n3. **`npm dist-tag add` still requires a fresh WebAuthn approval PER CALL**\n   regardless of the write-2FA setting — 6 individual browser approvals for a\n   3-package release (alpha + v3alpha × 3), not 1. Tell the human up front.\n- After every dist-tag call (or if unsure), verify with\n  `npm view <pkg> dist-tags --json` — don't trust the CLI's own stdout alone, since\n  a WebAuthn prompt that's still pending in the browser produces no terminal\n  output an agent can see.\n- Confirm the version actually landed (`npm view <pkg>@<version> version`) before\n  telling the user publishing succeeded, same reasoning: a mid-publish approval\n  that never gets answered fails silently from an agent's point of view.\n\n**Helpers signing key (required for `@claude-flow/cli` publish):** `npm publish`'s\n`prepublishOnly` runs `scripts/sign-helpers.mjs`, which needs a private key to sign\n`.claude/helpers/helpers.manifest.json`. The secret lives in GCP Secret Manager in the\n**`ruv-dev`** project (not `cognitum-20260110` or `claude-flow` — checked both, not there),\nsecret name `ruflo-helpers-signing-key`:\n\n```bash\ncd v3/@claude-flow/cli\nRUFLO_HELPERS_SIGNING_SECRET=ruflo-helpers-signing-key RUFLO_HELPERS_SIGNING_PROJECT=ruv-dev \\\n  npm publish\n```\n\n(`ruv-dev` also holds `ruflo-config-signing-key`; do not replace the existing\nauthenticated npm session with a token from another project.)\n\n**Handling the signing key without leaking it (learned 2026-07-14, hard way):**\nan earlier Windows path invoked `gcloud` without its required `.cmd` suffix. The\nfallback command printed the PEM into captured tool output and a session transcript.\nGCP secret v1 was destroyed and a fresh v2 was rotated in (commit 0052b1b06 /\nPR #2673). `sign-helpers.mjs` now selects `gcloud.cmd` on Windows and supports a\nstdin-only fallback. **Rules:**\n- NEVER invoke `gcloud secrets versions access` in a way that lets the payload reach\n  tool output. Use the built-in `RUFLO_HELPERS_SIGNING_SECRET` path above, or pipe\n  directly into the signer:\n  `gcloud secrets versions access latest --secret=ruflo-helpers-signing-key --project=ruv-dev | node scripts/sign-helpers.mjs --stdin-key`.\n- `--stdin-key` refuses interactive entry, validates Ed25519 key type, and never\n  echoes parser input. A local file via `RUFLO_HELPERS_SIGNING_KEY` remains the\n  air-gapped fallback.\n- If a rotation IS needed, keep the private half in `~/.ruflo/helpers-signing.key`\n  only, print ONLY the public half (via `Ed25519 pub export` from Node crypto), upload\n  new private via `gcloud secrets versions add … --data-file=`, then\n  `gcloud secrets versions destroy <old>` to make the old irrecoverable.\n\n**Windows `prepublishOnly` failure (learned 2026-07-14):** the CLI's `prepublishOnly`\nchain (`cp ../../../README.md ./README.md && rm -rf plugins && mkdir -p plugins && cp -r ...`)\nis POSIX-shell-only. On Windows, npm runs it via `cmd.exe /d /s /c` which chokes on\n`mkdir -p` (interprets `-p` as a directory name) and `cp -r` (no such command). Two\nworkarounds until the script is rewritten in cross-platform Node:\n1. Run the prep steps manually in Git Bash, then `npm publish --ignore-scripts`.\n2. Or use a POSIX shell for the whole publish: `SHELL=bash npm publish` — but this\n   doesn't always take effect on Windows depending on npm version.\nOption 1 is what worked for v3.29.0. Track proper fix in ruvnet/ruflo issue for\ncross-platform prepublish.\n\n**Concurrent-session helper corruption (real, observed, be paranoid):** multiple Claude Code\nsessions can have their own `npm exec @claude-flow/cli@latest mcp start` MCP server running\nconcurrently with `cwd` inside this repo (check with `readlink /proc/<pid>/cwd` on\n`pgrep -f \"npm exec @claude-flow/cli@latest mcp start\"`). If one of those resolved an older\ncached `@latest` (predating the `semver.gte` downgrade-guard in\n`helper-refresh.ts:autoRefreshHelpersIfStale`), it will silently overwrite this repo's\nhand-maintained `.claude/helpers/hook-handler.cjs` / `intelligence.cjs` (root AND package\ncopies) — and `helpers.manifest.json` + `.helpers-version` — with its own older bundled\ncontent, mid-session, with no warning. Observed live 2026-07-13: this happened *twice* in\none publish flow, once right after a manual revert and once right after signing (silently\ninvalidating a freshly-signed manifest). **Mitigation:** never trust the on-disk state of\nthose files between tool calls — `git diff --stat` them immediately before any `git add`/\n`sign-helpers.mjs`/`npm publish` step, `git checkout HEAD --` revert if dirty, and chain\nrevert → sign → verify → add → commit as ONE bash invocation (`&&`-joined) to minimize the\nrace window. `npm publish`'s own `prepublishOnly` re-signs fresh at pack time regardless, so\nwhat matters is the on-disk state at the *exact moment* `npm publish` runs, not before.\n\n```bash\n# Replace 3.7.1 below with your chosen stable version (patch/minor/major per the rules above)\n\n# STEP 1: Build and publish @claude-flow/cli\ncd v3/@claude-flow/cli\nnpm version 3.7.1 --no-git-tag-version\nnpm run build\nnpm publish                              # default tag is `latest` — no --tag flag\nnpm dist-tag add @claude-flow/cli@3.7.1 alpha     # historical compat\nnpm dist-tag add @claude-flow/cli@3.7.1 v3alpha   # historical compat\n\n# STEP 2: Publish claude-flow umbrella\ncd /Users/cohen/Projects/ruflo                    # or your repo root\nnpm version 3.7.1 --no-git-tag-version\nnpm publish\nnpm dist-tag add claude-flow@3.7.1 alpha\nnpm dist-tag add claude-flow@3.7.1 v3alpha\n\n# STEP 3: Publish ruflo wrapper (CRITICAL — DON'T FORGET — this is what users run)\ncd ruflo\nnpm version 3.7.1 --no-git-tag-version\nnpm publish\nnpm dist-tag add ruflo@3.7.1 alpha\nnpm dist-tag add ruflo@3.7.1 v3alpha\n```\n\n**Verification (run before telling user publishing is complete):**\n\n```bash\nfor pkg in @claude-flow/cli claude-flow ruflo; do\n  echo \"$pkg: $(npm view $pkg@latest version)\"\n  npm view $pkg dist-tags --json\ndone\n# All three must show latest === alpha === v3alpha === new version\n```\n\n### All Tags That Must Be Updated\n\n| Package | Tag | Command Users Run |\n|---------|-----|-------------------|\n| `@claude-flow/cli` | `latest` | `npx @claude-flow/cli@latest` |\n| `@claude-flow/cli` | `alpha` | `npx @claude-flow/cli@alpha` (legacy compat) |\n| `@claude-flow/cli` | `v3alpha` | `npx @claude-flow/cli@v3alpha` (legacy compat) |\n| `claude-flow` | `latest` | `npx claude-flow@latest` |\n| `claude-flow` | `alpha` | `npx claude-flow@alpha` (legacy compat) |\n| `claude-flow` | `v3alpha` | `npx claude-flow@v3alpha` (legacy compat) |\n| `ruflo` | `latest` | `npx ruflo@latest` |\n| `ruflo` | `alpha` | `npx ruflo@alpha` (legacy compat) |\n| `ruflo` | `v3alpha` | `npx ruflo@v3alpha` (legacy compat) |\n\n- Never forget the `ruflo` package — it's the thin wrapper users actually run via `npx ruflo`\n- The legacy `alpha` and `v3alpha` tags MUST stay pointed at the latest stable so old install commands keep working\n- `ruflo` source is in `/ruflo/` — it depends on `@claude-flow/cli`\n- 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)\n\n### GitHub Release after publish\n\nEvery stable bump SHOULD have a matching `gh release create v<version>` with consolidated release notes pointing at the gist if one exists. Example:\n\n```bash\ngit tag v3.7.1 main\ngit push origin v3.7.1\ngh release create v3.7.1 --title \"v3.7.1 — <one-line headline>\" \\\n  --notes-file /tmp/release-notes.md\n```\n\n## Plugin Registry Maintenance (IPFS/Pinata)\n\nThe plugin registry is stored on IPFS via Pinata for decentralized, immutable distribution.\n\n### Registry Location\n- **Current CID**: Stored in `v3/@claude-flow/cli/src/plugins/store/discovery.ts`\n- **Gateway**: `https://gateway.pinata.cloud/ipfs/{CID}`\n- **Format**: JSON with plugin metadata, categories, featured/trending lists\n\n### Required Environment Variables\nAdd to `.env` (NEVER commit actual values):\n```bash\nPINATA_API_KEY=your-api-key\nPINATA_API_SECRET=your-api-secret\nPINATA_API_JWT=your-jwt-token\n```\n\n## Plugin Registry Operations\n\n### Adding a New Plugin to Registry\n\n1. **Fetch current registry**:\n```bash\ncurl -s \"https://gateway.pinata.cloud/ipfs/$(grep LIVE_REGISTRY_CID v3/@claude-flow/cli/src/plugins/store/discovery.ts | cut -d\"'\" -f2)\" > /tmp/registry.json\n```\n\n2. **Add plugin entry** to the `plugins` array:\n```json\n{\n  \"id\": \"@claude-flow/your-plugin\",\n  \"name\": \"@claude-flow/your-plugin\",\n  \"displayName\": \"Your Plugin\",\n  \"description\": \"Plugin description\",\n  \"version\": \"1.0.0-alpha.1\",\n  \"size\": 100000,\n  \"checksum\": \"sha256:abc123\",\n  \"author\": {\"id\": \"claude-flow-team\", \"displayName\": \"Claude Flow Team\", \"verified\": true},\n  \"license\": \"MIT\",\n  \"categories\": [\"official\"],\n  \"tags\": [\"your\", \"tags\"],\n  \"downloads\": 0,\n  \"rating\": 5,\n  \"lastUpdated\": \"2026-01-25T00:00:00.000Z\",\n  \"minClaudeFlowVersion\": \"3.0.0\",\n  \"type\": \"integration\",\n  \"hooks\": [],\n  \"commands\": [],\n  \"permissions\": [\"memory\"],\n  \"exports\": [\"YourExport\"],\n  \"verified\": true,\n  \"trustLevel\": \"official\"\n}\n```\n\n3. **Update counts and arrays**:\n   - Increment `totalPlugins`\n   - Add to `official` array\n   - Add to `featured`/`newest` if applicable\n   - Update category `pluginCount`\n\n4. **Upload to Pinata** (read credentials from .env):\n```bash\n# Source credentials from .env\nPINATA_JWT=$(grep \"^PINATA_API_JWT=\" .env | cut -d'=' -f2-)\n\n# Upload updated registry\ncurl -X POST \"https://api.pinata.cloud/pinning/pinJSONToIPFS\" \\\n  -H \"Authorization: Bearer $PINATA_JWT\" \\\n  -H \"Content-Type: application/json\" \\\n  -d @/tmp/registry.json\n```\n\n5. **Update discovery.ts** with new CID:\n```typescript\nexport const LIVE_REGISTRY_CID = 'NEW_CID_FROM_PINATA';\n```\n\n6. **Also update demo registry** in discovery.ts `demoPluginRegistry` for offline fallback\n\n### Security Rules\n- NEVER hardcode API keys in scripts or source files\n- NEVER commit .env (already in .gitignore)\n- Always source credentials from environment at runtime\n- Always delete temporary scripts after one-time uploads\n\n### Verification\n```bash\n# Verify new registry is accessible\ncurl -s \"https://gateway.pinata.cloud/ipfs/{NEW_CID}\" | jq '.totalPlugins'\n```\n\n## MetaHarness Integration (ADR-150)\n\nRuflo 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.\n\n### Architectural constraint (load-bearing)\n\n**Ruflo remains operational if every MetaHarness package is removed.** Four rules:\n1. **Removable**: `npm ls --without @metaharness/*` must still produce a working CLI\n2. **Optional in package.json**: `@metaharness/*` packages MUST be optional peers, never normal dependencies\n3. **Graceful degradation**: every code path that touches MetaHarness catches `MODULE_NOT_FOUND` and falls back\n4. **CI gate**: `.github/workflows/no-metaharness-smoke.yml` enforces all three by static grep + runtime drill on every PR\n\n### Command + tool surface\n\n```bash\n# CLI subcommands (npx ruflo metaharness …)\nnpx ruflo metaharness score                      # 5-dim readiness scorecard\nnpx ruflo metaharness genome                     # 7-section categorical report\nnpx ruflo metaharness mcp-scan --fail-on high    # static security findings\nnpx ruflo metaharness threat-model               # enterprise threat report\nnpx ruflo metaharness oia-audit --alert-on-worst high\n                                                 # composite weekly audit → memory\nnpx ruflo metaharness audit-list --since 30d     # enumerate audit records\nnpx ruflo metaharness audit-trend \\              # diff two audits (drift)\n  --baseline-key <a> --current-key <b> --alert-on-worsening \\\n  --alert-on-distance-below 0.85               # iter 38 — structural-distance gate (ADR-152 §3.1)\nnpx ruflo metaharness similarity \\               # iter 36 — ADR-152 §3.1 weighted similarity\n  --a a.json --b b.json [--per-dimension] [--alert-below 0.5]\nnpx ruflo metaharness drift-from-history \\       # iter 53 — 1-command drift (composes 3 primitives)\n  [--baseline-since 7d] [--baseline-key <key>] [--baseline-file <path>] \\\n  [--threshold 0.95] [--alert-on-new-severity high] [--dry-run]\n                                                 # iter 66 — --baseline-key skips audit-list (~14x faster)\n                                                 # iter 67 — --baseline-file skips memory entirely (~19x faster)\n                                                 # iter 78 — --alert-on-new-severity adds orthogonal finding-severity gate\nnpx ruflo metaharness mint --name foo --template vertical:coding --confirm\nnpx ruflo metaharness redblue init               # @metaharness/redblue — scaffold redblue.yaml\nnpx ruflo metaharness redblue run --mock-judge --tests 10\n                                                 # $0 marker-fixture path (CI / offline)\nnpx ruflo metaharness redblue run --tests 50 --patch\n                                                 # real model judge (needs OPENROUTER_API_KEY,\n                                                 #   capped by max_cost_usd, default $3)\nnpx ruflo metaharness redblue attack prompt --count 3\n                                                 # preview generated attack cases (no target call)\nnpx ruflo metaharness redblue patch --mock-judge # baseline → blue-team patch → retest delta\nnpx ruflo metaharness redblue report --in report.json\n                                                 # render existing report as markdown\nnpx ruflo metaharness learn --host claude-code --model haiku --slice slices/lite.json\n                                                 # metaharness@0.3.0 / upstream ADR-235 —\n                                                 #   GEPA learning run; $0 dry-run default,\n                                                 #   --run to spend; needs a metaharness\n                                                 #   repo checkout (--repo / $METAHARNESS_REPO)\nnpx ruflo metaharness gepa --op genome           # darwin@0.8.0 GEPA library — load + validate\n                                                 #   the shipped cand-6 genome (or --path <f>)\nnpx ruflo metaharness gepa --op render           # genome → the system prompt it compiles to\nnpx ruflo metaharness gepa --op analyze --transcript run.json\n                                                 # classify failure modes in a transcript\nnpx ruflo metaharness evolve --bench .harness/bench.json\n                                                 # Darwin proposes candidates; governed gates decide\nnpx ruflo metaharness bench verify --path .harness/bench.json\n                                                 # create or verify stable benchmark corpora\nnpx ruflo metaharness flywheel run --proposer auto --max-concurrency 2\n                                                 # bounded concurrent evaluation; does not promote\nnpx ruflo metaharness flywheel receipts          # inspect immutable evaluation receipts\nnpx ruflo metaharness flywheel promote <receipt-id> \\\n  --public-key ./approved-ed25519-public.pem --confirm\n                                                 # explicit policy-authorized atomic promotion\n\n# Dedicated command\nnpx ruflo eject --name my-harness                # lift ruflo project → standalone harness\n                                                 # dry-run by default; refuses in-repo target\n\n# Doctor health check\nnpx ruflo doctor --component metaharness         # report metaharness availability + version\n\n# MCP tools (callable by Claude Code agents)\nmcp__claude-flow__metaharness_score\nmcp__claude-flow__metaharness_genome\nmcp__claude-flow__metaharness_mcp_scan\nmcp__claude-flow__metaharness_threat_model\nmcp__claude-flow__metaharness_oia_audit\nmcp__claude-flow__metaharness_audit_list\nmcp__claude-flow__metaharness_audit_trend\nmcp__claude-flow__metaharness_similarity          # iter 36 — ADR-152 §3.1 genome similarity\nmcp__claude-flow__metaharness_drift_from_history  # iter 53 — 1-command drift detection\nmcp__claude-flow__metaharness_bench               # ADR-153 — create/verify bench suites for evolve --bench\nmcp__claude-flow__metaharness_evolve              # MAP-Elites driver — evolve a harness across bench suites\nmcp__claude-flow__metaharness_security_bench      # security-focused benchmark suite gate\nmcp__claude-flow__metaharness_redblue             # @metaharness/redblue — adversarial red/blue LLM testing (init|run|patch|attack|report)\nmcp__claude-flow__metaharness_learn               # metaharness@0.3.0 — GEPA learning run ($0 dry-run default; run=true to spend)\nmcp__claude-flow__metaharness_gepa                # darwin@0.8.0 — GEPA genome ops (genome|validate|render|analyze); gepaOptimize stays library-only\nmcp__claude-flow__metaharness_flywheel            # ADR-322 — evaluate concurrently, inspect receipts/ledger, or explicitly promote\n```\n\n### Routing integration (ADR-148/149)\n\n`@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.\n\n### SelfEvolvingRouter parallel-logging (ADR-150 Phase 2)\n\nWhen `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:\n\n```bash\nnode plugins/ruflo-metaharness/scripts/router-parallel-analyze.mjs \\\n  --input .swarm/router-parallel.jsonl --strict\n```\n\nThe 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.\n\n### CI workflows\n\n- `metaharness-ci.yml` — score / mcp-scan / router-compat / eject-dryrun jobs on every PR touching `plugins/ruflo-metaharness/**`\n- `no-metaharness-smoke.yml` — enforces the four architectural-constraint rules above on every PR\n- `oia-audit-weekly.yml` — Sundays 04:17 UTC, runs composite audit, uploads 90-day artifact\n\n### Cross-references\n\n- [ADR-150](v3/docs/adr/ADR-150-metaharness-integration-surfaces.md) — decision + implementation notes\n- [Issue #2399](https://github.com/ruvnet/ruflo/issues/2399) — phase tracker\n- [Research gist](https://gist.github.com/ruvnet/19d166ff9acf368c9da4172d91ac9113) — graded evidence\n- Upstream: `github.com/ruvnet/agent-harness-generator`\n\n## Optional Plugins (20 Available)\n\nPlugins are distributed via IPFS and can be installed with the CLI. Browse and install from the official registry:\n\n```bash\n# List all available plugins\nnpx claude-flow@v3alpha plugins list\n\n# Install a plugin\nnpx claude-flow@v3alpha plugins install @claude-flow/plugin-name\n\n# Enable/disable\nnpx claude-flow@v3alpha plugins enable @claude-flow/plugin-name\nnpx claude-flow@v3alpha plugins disable @claude-flow/plugin-name\n```\n\n### Core Plugins\n\n| Plugin | Version | Description |\n|--------|---------|-------------|\n| `@claude-flow/embeddings` | 3.0.0-alpha.1 | Vector embeddings with sql.js, HNSW, hyperbolic support |\n| `@claude-flow/security` | 3.0.0-alpha.1 | Input validation, path security, CVE remediation |\n| `@claude-flow/claims` | 3.0.0-alpha.8 | Claims-based authorization (check, grant, revoke, list) |\n| `@claude-flow/neural` | 3.0.0-alpha.7 | Neural pattern training (SONA, MoE, EWC++) |\n| `@claude-flow/plugins` | 3.0.0-alpha.1 | Plugin system core (manager, discovery, store) |\n| `@claude-flow/performance` | 3.0.0-alpha.1 | Performance profiling and benchmarking |\n\n### Integration Plugins\n\n| Plugin | Version | Description |\n|--------|---------|-------------|\n| `@claude-flow/plugin-agentic-qe` | 3.0.0-alpha.4 | Agentic quality engineering integration |\n| `@claude-flow/plugin-prime-radiant` | 0.1.5 | Prime Radiant intelligence integration |\n| `@claude-flow/plugin-gastown-bridge` | 3.0.0-alpha.1 | Gastown bridge protocol integration |\n| `@claude-flow/teammate-plugin` | 1.0.0-alpha.1 | Multi-agent teammate coordination |\n| `@claude-flow/plugin-code-intelligence` | 0.1.0 | Advanced code analysis and intelligence |\n| `@claude-flow/plugin-test-intelligence` | 0.1.0 | Intelligent test generation and gap analysis |\n| `@claude-flow/plugin-perf-optimizer` | 0.1.0 | Performance optimization automation |\n| `@claude-flow/plugin-neural-coordinator` | 0.1.0 | Neural network coordination across agents |\n| `@claude-flow/plugin-cognitive-kernel` | 0.1.0 | Core cognitive processing kernel |\n| `@claude-flow/plugin-quantum-optimizer` | 0.1.0 | Quantum-inspired optimization algorithms |\n| `@claude-flow/plugin-hyperbolic-reasoning` | 0.1.0 | Hyperbolic space reasoning for hierarchical data |\n\n### Domain-Specific Plugins\n\n| Plugin | Version | Description |\n|--------|---------|-------------|\n| `@claude-flow/plugin-healthcare-clinical` | 0.1.0 | Healthcare clinical workflow automation |\n| `@claude-flow/plugin-financial-risk` | 0.1.0 | Financial risk assessment and modeling |\n| `@claude-flow/plugin-legal-contracts` | 0.1.0 | Legal contract analysis and generation |\n\n### Plugin Development\n\n```bash\n# Create a new plugin from template\nnpx claude-flow@v3alpha plugins create my-plugin\n\n# Test locally\nnpx claude-flow@v3alpha plugins install ./path/to/my-plugin\n\n# Publish to registry (requires Pinata credentials)\nnpx claude-flow@v3alpha plugins publish\n```\n\nRegistry source: IPFS via Pinata (`QmXbfEAaR7D2Ujm4GAkbwcGZQMHqAMpwDoje4583uNP834`)\n\n## Support\n\n- Documentation: https://github.com/ruvnet/claude-flow\n- Issues: https://github.com/ruvnet/claude-flow/issues\n\n---\n\nRemember: **Claude Flow coordinates, Claude Code creates!**\n\n## Gateway-Delegated Development (meta-llm dev-bridge)\n\nFor complex reasoning, architecture decisions, or hard bug-fixes, **delegate via the\n`metallm_delegate` MCP tool rather than solving inline.** The meta-llm gateway governs the\nwork: it routes cheap-tier-first, escalates genuinely-hard tasks to the frontier (Fable),\nand meters every call — so delegation is cost-governed and preserves the main session's context.\n\n- **Default to `cognitum-auto`** — the gateway picks the tier by difficulty. Only pass an\n  explicit tier (`cognitum-low|mid|high`) when you must force one.\n- Prompt-wrapping does **not** inflate cost — the gateway normalizes host scaffolds so an\n  everyday sub-task still routes to the cheap tier. Trust `cognitum-auto`.\n- Use **`metallm_delegate`** for agentic sub-tasks needing tools/files in a working dir\n  (its `cwd` is sandboxed); use **`metallm_ask`** for a single-shot question — it returns\n  the gateway's real metered cost + resolved tier/model in-band.\n- Reserve the main (inline) session for orchestration, integration, and final review;\n  push expensive per-sub-task reasoning through the gateway.\n\n**Setup (per developer, local — never committed):** register the `metallm-dev-bridge` MCP\nserver via a local `.mcp.json` (gitignored) and export your gateway key as `COGNITUM_DEV_KEY`\nin your shell. Build steps + the exact `.mcp.json` block are in the internal meta-llm\ndev-bridge README. **Never commit the key or an inline gateway URL.**\n\n### `ask` vs `delegate` — pick by task shape (load-bearing)\n\n**Use `metallm_ask` for single-shot facts, summaries, classification, and small code\nquestions. Use `metallm_delegate` only when the task needs autonomous multi-step execution\nor isolated agent context.**\n\nWhy the split is strict: `metallm_delegate` spawns a full `claude -p` sub-agent, which loads\nits entire harness context **even for a trivial task** — measured floor ≈ **$0.26/call**\n(~43k input tokens) before any real work. `metallm_ask` is a single gateway completion —\nmeasured ≈ **$0.0001** for a small query, ~2500× cheaper. So delegating casually is\nexpensive at volume; `delegate` pays off only when offloading the sub-task's context from\nthe main session is worth the floor. When in doubt, `ask`.\n\nRouting caveat (tracked): `metallm_ask` **auto** currently over-tiers some trivial prompts to\n`mid` (sonnet-5) instead of `low` — the bridge's `/v1/messages` path may miss ADR-236\nhost-normalization (meta-llm issue #38). Forced tiers work correctly; cost impact is small\nper call but real at volume.\n","AGENTS.md":"# Claude Flow V3 - Agent Guide\n\n> **For OpenAI Codex CLI** - Agentic AI Foundation standard\n> Skills: `$skill-name` | Config: `.agents/config.toml`\n\n---\n\n## 📢 TL;DR - READ THIS FIRST\n\n```\n╔═══════════════════════════════════════════════════════════════════════════╗\n║  1. claude-flow = LEDGER (tracks state, stores memory, coordinates)       ║\n║  2. Codex = EXECUTOR (writes code, runs commands, creates files)          ║\n║  3. NEVER stop after calling claude-flow - IMMEDIATELY continue working   ║\n║  4. If you need something BUILT/EXECUTED, YOU do it, not claude-flow      ║\n║  5. ALWAYS search memory BEFORE starting: memory search --query \"task\"    ║\n║  6. ALWAYS store patterns AFTER success: memory store --namespace patterns║\n╚═══════════════════════════════════════════════════════════════════════════╝\n```\n\n**Workflow (Use MCP Tools):**\n1. `memory_search(query=\"task keywords\")` → LEARN from past patterns (score > 0.7 = use it)\n2. `swarm_init(topology=\"hierarchical\")` → coordination record (instant)\n3. **YOU write the code / run the commands** ← THIS IS WHERE WORK HAPPENS\n4. `memory_store(key=\"pattern-x\", value=\"what worked\", namespace=\"patterns\")` → REMEMBER for next time\n\n---\n\n## Ruflo Policy-Governed Concurrent Codex Workflow\n\nRuflo is the coordination ledger and policy decision point. Codex agents are\nthe executors. Coordination records do not write code or run tests.\n\nUse `guidance_brain({ mode: \"recommend\", task: \"...\" })` to select Ruflo\ncapabilities from the live MCP registry. A registered tool is not necessarily\nconfigured, reachable, healthy, or authorized. If it is unavailable, continue\nwith compatible guidance tools, CLI discovery, and repository instructions.\n\n1. Recall relevant AgentDB memory and ADRs.\n2. Inspect source, runtime, dependencies, policy, and health.\n3. Route to the smallest capable topology, agents, skills, and tools.\n4. Plan acceptance criteria, safety envelope, ownership, and validation.\n5. Execute with Codex workers in isolated scopes; Ruflo records coordination.\n6. Test focused, regression, and failure paths.\n7. Validate types, security, policy, compatibility, and artifact integrity.\n8. Benchmark a source-bound candidate against a source-bound baseline.\n9. Optimize only measured bottlenecks without weakening safety.\n10. Bind claims and evidence into exact source/build receipts.\n11. Reconcile handoffs and disclose unresolved limitations.\n12. Publish only through a separately authorized release gate.\n\nHard invariants:\n\n- Never run two writers in one worktree.\n- Delegation may only reduce tools, servers, namespaces, network, spend,\n  concurrency, expiry, and depth.\n- Policy denial cancels dependent work before side effects.\n- MetaHarness may evaluate candidates concurrently, but only ADR-322A may\n  promote them and MetaHarness may never expand its own SafetyEnvelope.\n- Do not commit, push, merge, release, or remove worktrees unless authorized.\n- Existing installations migrate in `legacy` policy mode; use `observe` before\n  switching to `enforce`.\n\nRepository harness integration:\n\n- If tracked repository instructions define a collaboration harness, start its\n  session only after assigning an isolated worktree.\n- Inspect existing claims, acquire exact paths/resources/ports, renew leases,\n  check acknowledged inbox messages at integration boundaries, and release ownership on\n  handoff or exit.\n- A repository lease coordinates ownership; it does not grant authorization.\n  Protected work still requires the ADR-324/325 action capability and current\n  fencing epoch.\n- In-memory reference adapters demonstrate semantics; they are not distributed,\n  restart-durable release authorities.\n- Heartbeats and lease expiry establish liveness; a PID is diagnostic only.\n- `HEAD` alone is not an exact source-state identity in a dirty worktree.\n  Release evidence must bind a clean commit or an immutable snapshot of tracked\n  and untracked changes.\n\nUseful checks:\n\n```bash\nnpx ruflo policy status\nnpx ruflo policy verify\nnpx ruflo metaharness flywheel status\n```\n\nRepository release contract:\n\n- The stable public train is exactly `@claude-flow/cli`, `claude-flow`, and\n  `ruflo`; internal `@claude-flow/*` components are bundled and are not part of\n  a normal standalone publish.\n- Publish from a clean, reviewed source state in that order.\n- Only the CLI publish receives the helper-signing configuration from\n  `ruv-dev`; use the existing authenticated npm session for publication.\n- Run `node scripts/audit-umbrella-version-lockstep.mjs`, verify all three\n  registry versions, and align `latest`, `alpha`, and `v3alpha`.\n\n---\n\n## 🚨 CRITICAL: CODEX DOES THE WORK, CLAUDE-FLOW ORCHESTRATES\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│  CLAUDE-FLOW = ORCHESTRATOR (tracks state, coordinates)     │\n│  CODEX = WORKER (writes code, runs commands, implements)    │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### ❌ WRONG: Expecting claude-flow to execute tasks\n```bash\nnpx claude-flow swarm start --objective \"Build API\"\n# WRONG: Waiting for claude-flow to build the API\n# Claude-flow does NOT execute code!\n```\n\n### ✅ CORRECT: Codex executes, claude-flow tracks\n```bash\n# 1. Tell claude-flow what you're doing (optional coordination)\nnpx claude-flow swarm init --topology hierarchical --max-agents 1\nnpx claude-flow agent spawn --type coder --name codex-worker\n\n# 2. YOU (CODEX) DO THE ACTUAL WORK:\nmkdir -p src\ncat > src/api.ts << 'EOF'\nexport function hello() { return \"Hello World\"; }\nEOF\n\n# 3. Report to claude-flow what you did (optional)\nnpx claude-flow memory store --key \"api-created\" --value \"src/api.ts\" --namespace results\n```\n\n### The Division of Labor\n\n| Component | Role | Examples |\n|-----------|------|----------|\n| **CODEX** | EXECUTES | Write files, run tests, create code, shell commands |\n| **claude-flow** | ORCHESTRATES | Track agents, store memory, coordinate tasks |\n\n---\n\n## ⛔ DON'T STOP AFTER CALLING CLAUDE-FLOW\n\n```\n┌─────────────────────────────────────────────────────────────────────────┐\n│  ❌ WRONG: Call claude-flow → STOP → Wait for results                   │\n│  ✅ RIGHT: Call claude-flow → IMMEDIATELY continue → YOU do the work    │\n└─────────────────────────────────────────────────────────────────────────┘\n```\n\n### ❌ WRONG Pattern (Stopping)\n```bash\nnpx claude-flow swarm init --topology hierarchical\nnpx claude-flow agent spawn --type coder --name worker-1\nnpx claude-flow swarm start --objective \"Build hello world\"\n# WRONG: Codex stops here and waits for something to happen\n# Nothing will happen! Claude-flow doesn't execute code!\n```\n\n### ✅ CORRECT Pattern (Continue Immediately)\n```bash\n# Step 1: Coordination (optional)\nnpx claude-flow swarm init --topology hierarchical\nnpx claude-flow agent spawn --type coder --name worker-1\n\n# Step 2: IMMEDIATELY DO THE WORK YOURSELF - DON'T WAIT!\necho 'console.log(\"Hello World!\");' > hello.js\nnode hello.js\n\n# Step 3: Report what you did\nnpx claude-flow memory store --key \"result\" --value \"Hello World printed\" --namespace results\n```\n\n### The Rule\n**After ANY claude-flow command, IMMEDIATELY continue with your own work.**\n\nClaude-flow commands return instantly. They create coordination RECORDS only.\nYou must ALWAYS follow up with YOUR OWN execution.\n\n| After This... | IMMEDIATELY Do This... |\n|---------------|----------------------|\n| `swarm init` | Start writing code |\n| `agent spawn` | Continue implementation |\n| `task create` | Execute the task yourself |\n| `swarm start` | Begin actual work |\n\n---\n\n### When to Use Claude-Flow Commands\n\n| Use Case | Claude-Flow Command | Then Codex Does |\n|----------|---------------------|-----------------|\n| Track progress | `memory store --key \"step1\" --value \"done\"` | Continue to next step |\n| Multi-step tasks | `task create --description \"step 2\"` | Execute step 2 |\n| Store results | `memory store --key \"output\" --value \"...\"` | Move on |\n| Coordinate | `swarm init` | Start working |\n\n### Hello World - Correct Pattern\n\n```bash\n# STEP 1: Optional - register with orchestrator\nnpx claude-flow swarm init --topology mesh --max-agents 1\n\n# STEP 2: CODEX DOES THE WORK\necho 'console.log(\"Hello World!\");' > hello.js\nnode hello.js\n\n# STEP 3: Optional - report completion\nnpx claude-flow memory store --key \"hello-result\" --value \"printed Hello World\" --namespace results\n```\n\n**REMEMBER: If you need something DONE, YOU do it. Claude-flow just tracks.**\n\n---\n\n## ⚡ QUICK COMMANDS (NO DISCOVERY NEEDED)\n\n### Spawn N-Agent Swarm (Copy-Paste Ready)\n\n```bash\n# 5-AGENT SWARM - Run these commands in sequence:\nnpx claude-flow swarm init --topology hierarchical --max-agents 8\nnpx claude-flow agent spawn --type coordinator --name coord-1\nnpx claude-flow agent spawn --type coder --name coder-1\nnpx claude-flow agent spawn --type coder --name coder-2\nnpx claude-flow agent spawn --type tester --name tester-1\nnpx claude-flow agent spawn --type reviewer --name reviewer-1\nnpx claude-flow swarm start --objective \"Your task here\" --strategy development\n```\n\n### Common Swarm Patterns\n\n| Task | Exact Command |\n|------|---------------|\n| Init hierarchical swarm | `npx claude-flow swarm init --topology hierarchical --max-agents 8` |\n| Init mesh swarm | `npx claude-flow swarm init --topology mesh --max-agents 5` |\n| Init V3 mode (15 agents) | `npx claude-flow swarm init --v3-mode` |\n| Spawn coder | `npx claude-flow agent spawn --type coder --name coder-1` |\n| Spawn tester | `npx claude-flow agent spawn --type tester --name tester-1` |\n| Spawn coordinator | `npx claude-flow agent spawn --type coordinator --name coord-1` |\n| Spawn architect | `npx claude-flow agent spawn --type architect --name arch-1` |\n| Spawn reviewer | `npx claude-flow agent spawn --type reviewer --name rev-1` |\n| Spawn researcher | `npx claude-flow agent spawn --type researcher --name res-1` |\n| Start swarm | `npx claude-flow swarm start --objective \"task\" --strategy development` |\n| Check swarm status | `npx claude-flow swarm status` |\n| List agents | `npx claude-flow agent list` |\n| Stop swarm | `npx claude-flow swarm stop` |\n\n### Agent Types (Use with `--type`)\n\n| Type | Purpose |\n|------|---------|\n| `coordinator` | Orchestrates other agents |\n| `coder` | Writes code |\n| `tester` | Writes tests |\n| `reviewer` | Reviews code |\n| `architect` | Designs systems |\n| `researcher` | Analyzes requirements |\n| `security-architect` | Security design |\n| `performance-engineer` | Optimization |\n\n### Task Commands\n\n| Action | Command |\n|--------|---------|\n| Create task | `npx claude-flow task create --type implementation --description \"desc\"` |\n| List tasks | `npx claude-flow task list` |\n| Assign task | `npx claude-flow task assign TASK_ID --agent AGENT_NAME` |\n| Task status | `npx claude-flow task status TASK_ID` |\n| Cancel task | `npx claude-flow task cancel TASK_ID` |\n\n### Memory Commands\n\n| Action | Command |\n|--------|---------|\n| Store | `npx claude-flow memory store --key \"key\" --value \"value\" --namespace patterns` |\n| Search | `npx claude-flow memory search --query \"search terms\"` |\n| List | `npx claude-flow memory list --namespace patterns` |\n| Retrieve | `npx claude-flow memory retrieve --key \"key\"` |\n\n---\n\n## 🚀 SWARM RECIPES\n\n### Recipe 1: Hello World Test (COMPLETE EXAMPLE)\n\n**Step 1: Setup coordination** (returns instantly - don't stop!)\n```bash\nnpx claude-flow swarm init --topology mesh --max-agents 5\nnpx claude-flow agent spawn --type coder --name hello-main\n# ⚠️ DON'T STOP HERE - CONTINUE IMMEDIATELY TO STEP 2\n```\n\n**Step 2: YOU (Codex) execute the task** (THIS IS THE REAL WORK)\n```bash\n# ✅ YOU create the file\necho 'console.log(\"Hello World from Swarm!\");' > /tmp/hello-swarm.js\n\n# ✅ YOU execute it\nnode /tmp/hello-swarm.js\n# Output: Hello World from Swarm!\n```\n\n**Step 3: Report completion** (optional - store results)\n```bash\nnpx claude-flow memory store --key \"hello-world-result\" --value \"Executed: Hello World from Swarm!\" --namespace results\n```\n\n### Recipe 1b: 5-Agent Concurrent Hello World (COMPLETE)\n```bash\n# COORDINATION (instant - creates records only)\nnpx claude-flow swarm init --topology hierarchical --max-agents 5\nfor i in 1 2 3 4 5; do\n  npx claude-flow agent spawn --type coder --name \"worker-$i\"\ndone\n\n# ⚠️ NOW YOU DO THE ACTUAL CONCURRENT WORK:\nfor i in 1 2 3 4 5; do\n  (echo \"Worker $i: Hello World!\" && sleep 0.$i) &\ndone\nwait\necho \"All 5 workers completed!\"\n\n# REPORT (optional)\nnpx claude-flow memory store --key \"concurrent-result\" --value \"5 workers completed\" --namespace results\n```\n\n### Recipe 1b: Hello World (Single Command Block)\n```bash\n# All-in-one execution\nnpx claude-flow swarm init --topology mesh --max-agents 5 && \\\nnpx claude-flow agent spawn --type coder --name hello-main && \\\nnpx claude-flow swarm start --objective \"Print hello world\" --strategy development && \\\necho 'console.log(\"Hello World from Swarm!\");' > /tmp/hello-swarm.js && \\\nnode /tmp/hello-swarm.js && \\\nnpx claude-flow memory store --key \"hello-world-result\" --value \"Success\" --namespace results\n```\n\n### Recipe 2: Feature Implementation (6 Agents)\n```bash\nnpx claude-flow swarm init --topology hierarchical --max-agents 8\nnpx claude-flow agent spawn --type coordinator --name lead\nnpx claude-flow agent spawn --type architect --name arch\nnpx claude-flow agent spawn --type coder --name impl-1\nnpx claude-flow agent spawn --type coder --name impl-2\nnpx claude-flow agent spawn --type tester --name test\nnpx claude-flow agent spawn --type reviewer --name review\nnpx claude-flow swarm start --objective \"Implement [feature]\" --strategy development\n```\n\n### Recipe 3: Bug Fix (4 Agents)\n```bash\nnpx claude-flow swarm init --topology hierarchical --max-agents 4\nnpx claude-flow agent spawn --type coordinator --name lead\nnpx claude-flow agent spawn --type researcher --name debug\nnpx claude-flow agent spawn --type coder --name fix\nnpx claude-flow agent spawn --type tester --name verify\nnpx claude-flow swarm start --objective \"Fix [bug]\" --strategy development\n```\n\n### Recipe 4: Security Audit (3 Agents)\n```bash\nnpx claude-flow swarm init --topology hierarchical --max-agents 4\nnpx claude-flow agent spawn --type coordinator --name lead\nnpx claude-flow agent spawn --type security-architect --name audit\nnpx claude-flow agent spawn --type reviewer --name review\nnpx claude-flow swarm start --objective \"Security audit\" --strategy development\n```\n\n### Recipe 5: V3 Full Coordination (15 Agents)\n```bash\nnpx claude-flow swarm init --v3-mode\nnpx claude-flow swarm coordinate --agents 15\n```\n\n---\n\n## 📋 BEHAVIORAL RULES\n\n- **YOU (CODEX) execute tasks** - claude-flow only orchestrates\n- Do what is asked; nothing more, nothing less\n- NEVER create files unless absolutely necessary\n- ALWAYS prefer editing existing files\n- NEVER save to root folder\n- NEVER commit secrets or .env files\n- ALWAYS read a file before editing it\n- NEVER wait for claude-flow to \"do work\" - it doesn't execute, YOU do\n- Use claude-flow commands to TRACK progress, not to EXECUTE tasks\n\n## 📁 FILE ORGANIZATION\n\n| Directory | Purpose |\n|-----------|---------|\n| `/src` | Source code |\n| `/tests` | Test files |\n| `/docs` | Documentation |\n| `/config` | Configuration |\n| `/scripts` | Utility scripts |\n\n## 🎯 WHEN TO USE SWARMS\n\n**USE SWARM:**\n- Multiple files (3+)\n- New feature implementation\n- Cross-module refactoring\n- API changes with tests\n- Security-related changes\n- Performance optimization\n\n**SKIP SWARM:**\n- Single file edits\n- Simple bug fixes (1-2 lines)\n- Documentation updates\n- Configuration changes\n\n---\n\n## 🔧 CLI REFERENCE\n\n### Swarm Commands\n```bash\nnpx claude-flow swarm init [--topology TYPE] [--max-agents N] [--v3-mode]\nnpx claude-flow swarm start --objective \"task\" --strategy [development|research]\nnpx claude-flow swarm status [SWARM_ID]\nnpx claude-flow swarm stop [SWARM_ID]\nnpx claude-flow swarm scale --count N\nnpx claude-flow swarm coordinate --agents N\n```\n\n### Agent Commands\n```bash\nnpx claude-flow agent spawn --type TYPE --name NAME\nnpx claude-flow agent list [--filter active|idle|busy]\nnpx claude-flow agent status AGENT_ID\nnpx claude-flow agent stop AGENT_ID\nnpx claude-flow agent metrics [AGENT_ID]\nnpx claude-flow agent health\nnpx claude-flow agent logs AGENT_ID\n```\n\n### Task Commands\n```bash\nnpx claude-flow task create --type TYPE --description \"desc\"\nnpx claude-flow task list [--all]\nnpx claude-flow task status TASK_ID\nnpx claude-flow task assign TASK_ID --agent AGENT_NAME\nnpx claude-flow task cancel TASK_ID\nnpx claude-flow task retry TASK_ID\n```\n\n### Memory Commands\n```bash\nnpx claude-flow memory store --key KEY --value VALUE [--namespace NS]\nnpx claude-flow memory search --query \"terms\" [--namespace NS]\nnpx claude-flow memory list [--namespace NS]\nnpx claude-flow memory retrieve --key KEY [--namespace NS]\nnpx claude-flow memory init [--force]\n```\n\n### Hooks Commands\n```bash\nnpx claude-flow hooks pre-task --description \"task\"\nnpx claude-flow hooks post-task --task-id ID --success true\nnpx claude-flow hooks route --task \"task\"\nnpx claude-flow hooks session-start --session-id ID\nnpx claude-flow hooks session-end --export-metrics true\nnpx claude-flow hooks worker list\nnpx claude-flow hooks worker dispatch --trigger audit\n```\n\n### System Commands\n```bash\nnpx claude-flow init [--wizard] [--codex] [--full]\nnpx claude-flow daemon start\nnpx claude-flow daemon stop\nnpx claude-flow daemon status\nnpx claude-flow doctor [--fix]\nnpx claude-flow status\nnpx claude-flow mcp start\n```\n\n---\n\n## 🔌 TOPOLOGIES\n\n| Topology | Use Case | Command Flag |\n|----------|----------|--------------|\n| `hierarchical` | Coordinated teams, anti-drift | `--topology hierarchical` |\n| `mesh` | Peer-to-peer, equal agents | `--topology mesh` |\n| `hierarchical-mesh` | Hybrid (recommended for V3) | `--topology hierarchical-mesh` |\n| `ring` | Sequential processing | `--topology ring` |\n| `star` | Central coordinator | `--topology star` |\n| `adaptive` | Dynamic switching | `--topology adaptive` |\n\n## 🤖 AGENT TYPES\n\n### Core\n`coordinator`, `coder`, `tester`, `reviewer`, `architect`, `researcher`\n\n### Specialized\n`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`\n\n### Swarm Coordination\n`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`\n\n### Consensus\n`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`\n\n---\n\n## ⚙️ CONFIGURATION\n\n### Default Swarm Config\n- Topology: `hierarchical`\n- Max Agents: 8\n- Strategy: `specialized`\n- Consensus: `raft`\n- Memory: `hybrid`\n\n### Environment Variables\n```bash\nCLAUDE_FLOW_CONFIG=./claude-flow.config.json\nCLAUDE_FLOW_LOG_LEVEL=info\nCLAUDE_FLOW_MEMORY_BACKEND=hybrid\n```\n\n---\n\n## 🔗 SKILLS\n\nInvoke with `$skill-name`:\n\n| Skill | Purpose |\n|-------|---------|\n| `$swarm-orchestration` | Multi-agent coordination |\n| `$memory-management` | Pattern storage/retrieval |\n| `$sparc-methodology` | Structured development |\n| `$security-audit` | Security scanning |\n| `$performance-analysis` | Profiling |\n| `$github-automation` | CI/CD management |\n| `$hive-mind` | Byzantine consensus |\n| `$neural-training` | Pattern learning |\n\n---\n\n---\n\n## 🔌 MCP INTEGRATION (Learning & Coordination)\n\nCodex doesn't have native hooks like Claude Code, but uses **MCP (Model Context Protocol)** for learning and coordination.\n\n### MCP Auto-Registration\n\nWhen you run `npx claude-flow init --codex`, the MCP server is **automatically registered** with Codex.\n\n```bash\n# Verify MCP is registered:\ncodex mcp list\n\n# Expected output:\n# Name         Command  Args                   Status\n# claude-flow  npx      claude-flow mcp start  enabled\n\n# If not present, add manually:\ncodex mcp add claude-flow -- npx claude-flow mcp start\n```\n\n### Test MCP Connection\n```bash\n# Test MCP server starts correctly:\nnpx claude-flow mcp start --test\n```\n\n### MCP Tools Available\nOnce added, Codex can use these tools via MCP:\n\n**Coordination:**\n| Tool | Purpose |\n|------|---------|\n| `swarm_init` | Initialize swarm (topology, maxAgents) |\n| `swarm_status` | Check swarm state |\n| `agent_spawn` | Register agent roles |\n| `agent_status` | Check agent state |\n| `task_orchestrate` | Coordinate multi-agent tasks |\n\n**Learning & Memory (USE THESE!):**\n| Tool | Purpose | When |\n|------|---------|------|\n| `memory_search` | Semantic vector search | BEFORE every task |\n| `memory_store` | Store patterns with embeddings | AFTER success |\n| `memory_retrieve` | Get by exact key | When key is known |\n| `neural_train` | Train on patterns | Periodic improvement |\n| `neural_status` | Check learning state | Debugging |\n\n**Hive Mind (Advanced):**\n| Tool | Purpose |\n|------|---------|\n| `hive-mind_init` | Byzantine consensus swarm |\n| `hive-mind_spawn` | Spawn hive workers |\n| `hive-mind_broadcast` | Message all workers |\n\n### Self-Learning via MCP Tools (PREFERRED)\n\nUse MCP tools directly - faster than CLI commands:\n\n**BEFORE starting any task - SEARCH for patterns:**\n```\nUse tool: memory_search\n  query: \"keywords related to your task\"\n  namespace: \"patterns\"\n```\n\n**AFTER completing successfully - STORE the pattern:**\n```\nUse tool: memory_store\n  key: \"pattern-[descriptive-name]\"\n  value: \"What worked: approach, code patterns, gotchas\"\n  namespace: \"patterns\"\n```\n\n### MCP Learning Workflow (Use This!)\n\n```\n1. LEARN: memory_search(query=\"task keywords\", namespace=\"patterns\")\n   → If score > 0.7, USE that pattern\n\n2. COORDINATE: swarm_init(topology=\"hierarchical\")\n   → agent_spawn(type=\"coder\", name=\"worker-1\")\n\n3. EXECUTE: YOU write the code, run commands, create files\n\n4. REMEMBER: memory_store(key=\"pattern-x\", value=\"what worked\", namespace=\"patterns\")\n```\n\n### MCP Tools for Learning\n\n| Tool | Purpose | When to Use |\n|------|---------|-------------|\n| `memory_search` | Find similar past patterns | BEFORE starting any task |\n| `memory_store` | Save successful patterns | AFTER completing a task |\n| `memory_retrieve` | Get specific pattern by key | When you know the exact key |\n| `neural_train` | Train on successful patterns | After multiple successes |\n\n### Example: Learning-Enabled Task\n\n```\nSTEP 1 - LEARN:\nUse tool: memory_search\n  query: \"validation utility function\"\n  namespace: \"patterns\"\n\n→ Found: pattern-email-validator (score: 0.82)\n→ Use this pattern as reference!\n\nSTEP 2 - COORDINATE:\nUse tool: swarm_init with topology=\"hierarchical\", maxAgents=3\n\nSTEP 3 - EXECUTE:\nYOU create the files:\n  echo 'export function validate(x) { ... }' > /tmp/validator.js\n  node --test /tmp/validator.js\n\nSTEP 4 - REMEMBER:\nUse tool: memory_store\n  key: \"pattern-phone-validator\"\n  value: \"Phone validation: regex /^\\+?[\\d\\s-]{10,}$/, normalize first, test edge cases\"\n  namespace: \"patterns\"\n```\n\n### Vector Search Tips\n- Searches are SEMANTIC (meaning-based, not just keywords)\n- Score > 0.7 = strong match, use that pattern\n- Score 0.5-0.7 = partial match, adapt as needed\n- Store DETAILED values for better future retrieval\n\n### CLI Fallback (if MCP unavailable)\n```bash\nnpx claude-flow memory search --query \"keywords\" --namespace patterns\nnpx claude-flow memory store --key \"pattern-x\" --value \"what worked\" --namespace patterns\n```\n\n### Coordination via MCP\n\nWhen claude-flow is added as MCP server, Codex can call tools directly:\n```\nUse tool: swarm_init with topology=\"hierarchical\"\nUse tool: memory_store with key=\"result\" value=\"success\"\n```\n\n### config.toml MCP Setup\n```toml\n# ~/.codex/config.toml\n[mcp_servers.claude-flow]\ncommand = \"npx\"\nargs = [\"claude-flow\", \"mcp\", \"start\"]\nenabled = true\n```\n\n---\n\n## 📚 SUPPORT\n\n- Docs: https://github.com/ruvnet/claude-flow\n- Issues: https://github.com/ruvnet/claude-flow/issues\n\n**Remember: Codex executes, claude-flow orchestrates!**\n"},"files":{"CLAUDE.md":"# Claude Code Configuration - Ruflo V3\n\n> Public release train: `@claude-flow/cli`, `claude-flow`, and `ruflo`.\n> Use package manifests and the registry as version truth; do not copy stale\n> version or capability counts into agent guidance.\n\n## Behavioral Rules (Always Enforced)\n\n- Do what has been asked; nothing more, nothing less\n- NEVER create files unless they're absolutely necessary for achieving your goal\n- ALWAYS prefer editing an existing file to creating a new one\n- NEVER proactively create documentation files (*.md) or README files unless explicitly requested\n- NEVER save working files, text/mds, or tests to the root folder\n- Never continuously check status after spawning a swarm — wait for results\n- ALWAYS read a file before editing it\n- NEVER commit secrets, credentials, or .env files\n\n## Capability Brain and Governed Implementation\n\nRuflo is the coordination ledger and policy decision point. Claude Code\nexecutes code, tests, commands, and file changes. A Ruflo coordination call\nrecords work; it does not perform the implementation.\n\nWhen registered, call\n`guidance_brain({ mode: \"recommend\", task: \"...\" })` before complex Ruflo\nwork. Use its live registry rather than guessing tool names. Treat\n`registered`, `configured`, `reachable`, `healthy`, and `authorized` as\nseparate facts. If unavailable, continue with compatible guidance tools, CLI\ndiscovery, and these repository instructions.\n\nUse this loop: recall → inspect → route → plan → execute → test → validate →\nbenchmark → optimize → receipt → handoff → separately authorized publish.\n\n## File Organization\n\n- NEVER save to root folder — use the directories below\n- Use `/src` for source code files\n- Use `/tests` for test files\n- Use `/docs` for documentation and markdown files\n- Use `/config` for configuration files\n- Use `/scripts` for utility scripts\n- Use `/examples` for example code\n\n## Project Architecture\n\n- Follow Domain-Driven Design with bounded contexts\n- Keep files under 500 lines\n- Use typed interfaces for all public APIs\n- Prefer TDD London School (mock-first) for new code\n- Use event sourcing for state changes\n- Ensure input validation at system boundaries\n\n### Key Packages\n\n| Package | Path | Purpose |\n|---------|------|---------|\n| `@claude-flow/cli` | `v3/@claude-flow/cli/` | CLI entry point (26 commands) |\n| `@claude-flow/codex` | `v3/@claude-flow/codex/` | Dual-mode Claude + Codex collaboration |\n| `@claude-flow/guidance` | `v3/@claude-flow/guidance/` | Governance control plane |\n| `@claude-flow/hooks` | `v3/@claude-flow/hooks/` | 17 hooks + 12 workers |\n| `@claude-flow/memory` | `v3/@claude-flow/memory/` | AgentDB + HNSW search |\n| `@claude-flow/security` | `v3/@claude-flow/security/` | Input validation, CVE remediation |\n\n## Concurrent Automated Development\n\n- Parallelize independent research, tests, reviews, and non-overlapping\n  implementation.\n- Never allow two writers in one worktree. Give every writing agent an isolated\n  worktree and explicit file ownership.\n- Read-only agents may share a checkout; writing agents may not.\n- Only the integration owner edits shared manifests and lockfiles or reconciles\n  overlapping changes.\n- Continue independent local work after spawning agents; wait only when a real\n  dependency blocks progress. Do not repeatedly poll.\n- A lease or work claim coordinates ownership; it never grants authority.\n- Bind tests, benchmarks, policy decisions, and handoffs to an exact clean\n  commit or immutable dirty-worktree snapshot.\n- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose and\n  evaluate candidates, but cannot self-promote or expand tools, network,\n  secrets, spend, concurrency, or release authority.\n\n---\n\n## Swarm Orchestration\n\n- MUST initialize the swarm using MCP tools when starting complex tasks\n- MUST spawn concurrent agents using Claude Code's Task tool\n- Never use MCP tools alone for execution — Task tool agents do the actual work\n\n### MCP + Task Tool in SAME Message\n\n- MUST call MCP tools AND Task tool in ONE message for complex work\n- Always call MCP first, then IMMEDIATELY call Task tool to spawn agents\n\n### 3-Tier Model Routing (ADR-026, ADR-143)\n\n| Tier | Handler | Latency | Cost | Use Cases |\n|------|---------|---------|------|-----------|\n| **1** | Deterministic codemod | ~1ms | $0 | Structural transforms with **no LLM**: `var-to-const`, `remove-console`, `add-logging` |\n| **2** | Haiku | ~500ms | $0.0002 | Simple tasks, low complexity (<30%) |\n| **3** | Sonnet/Opus | 2-5s | $0.003-0.015 | Complex reasoning, architecture, security (>30%) |\n\n- Always check for `[CODEMOD_AVAILABLE]` or `[TASK_MODEL_RECOMMENDATION]` before spawning agents\n- 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`\n- `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)\n- 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 path\n\n## Swarm Configuration & Anti-Drift\n\n### Anti-Drift Coding Swarm (PREFERRED DEFAULT)\n\n- ALWAYS use hierarchical topology for coding swarms\n- Keep maxAgents at 6-8 for tight coordination\n- Use specialized strategy for clear role boundaries\n- Use `raft` consensus for hive-mind (leader maintains authoritative state)\n- Run frequent checkpoints via `post-task` hooks\n- Keep shared memory namespace for all agents\n- Keep task cycles short with verification gates\n\n```javascript\nmcp__ruv-swarm__swarm_init({\n  topology: \"hierarchical\",\n  maxAgents: 8,\n  strategy: \"specialized\"\n})\n```\n\n## Dual-Mode Collaboration (Claude Code + Codex)\n\nThis 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.\n\n### Why Dual-Mode?\n\n| Single Platform | Dual-Mode Collaboration |\n|----------------|------------------------|\n| One model's perspective | Two AI platforms cross-validating |\n| Limited reasoning styles | Complementary strengths |\n| No external verification | Built-in code review |\n| Sequential workflows | Parallel execution |\n\n### Dual-Mode Swarm Protocol\n\nFor complex tasks, spawn both Claude and Codex workers in parallel:\n\n```javascript\n// STEP 1: Initialize dual-mode swarm\nmcp__ruv-swarm__swarm_init({\n  topology: \"hierarchical\",\n  maxAgents: 8,\n  strategy: \"specialized\"\n})\n\n// STEP 2: Spawn BOTH platforms in parallel via Task tool\n// 🔵 Claude Code workers (architecture, security, testing)\nTask(\"Architect\", \"Design the implementation. Store design in memory namespace 'collaboration'.\", \"system-architect\")\nTask(\"Tester\", \"Write tests based on architect's design. Read from 'collaboration' namespace.\", \"tester\")\nTask(\"Reviewer\", \"Review code quality and security. Store findings in 'collaboration'.\", \"reviewer\")\n\n// 🟢 Codex workers (implementation, optimization)\n// Spawn via CLI for Codex platform\nBash(\"npx claude-flow-codex dual run --worker 'codex:coder:Implement the solution based on architect design' --namespace collaboration\")\nBash(\"npx claude-flow-codex dual run --worker 'codex:optimizer:Optimize performance based on implementation' --namespace collaboration\")\n\n// STEP 3: Coordinate via shared memory\nBash(\"npx claude-flow@v3alpha memory store --namespace collaboration --key 'task-context' --value '[task description]'\")\n```\n\n### Collaboration Templates (Pre-Built Pipelines)\n\n| Template | Workers | Pipeline |\n|----------|---------|----------|\n| `feature` | 🔵 Architect → 🟢 Coder → 🔵 Tester → 🟢 Reviewer | Full feature development |\n| `security` | 🔵 Analyst → 🟢 Scanner → 🔵 Reporter | Security audit workflow |\n| `refactor` | 🔵 Architect → 🟢 Refactorer → 🔵 Tester | Code modernization |\n| `bugfix` | 🔵 Researcher → 🟢 Coder → 🔵 Tester | Bug investigation & fix |\n\n### Dual-Mode CLI Commands\n\n```bash\n# Run a collaboration template\nnpx claude-flow-codex dual run feature --task \"Add user authentication with OAuth\"\nnpx claude-flow-codex dual run security --target \"./src\"\nnpx claude-flow-codex dual run refactor --target \"./src/legacy\"\n\n# Custom multi-platform swarm\nnpx claude-flow-codex dual run \\\n  --worker \"claude:architect:Design the API structure\" \\\n  --worker \"codex:coder:Implement REST endpoints\" \\\n  --worker \"claude:tester:Write integration tests\" \\\n  --worker \"codex:reviewer:Review code quality\" \\\n  --namespace \"api-feature\"\n\n# Check collaboration status\nnpx claude-flow-codex dual status\n\n# List available templates\nnpx claude-flow-codex dual templates\n```\n\n### Shared Memory Coordination\n\nAll workers share state via the `collaboration` namespace:\n\n```bash\n# Store context for cross-platform sharing\nnpx claude-flow@v3alpha memory store --namespace collaboration --key \"design-decisions\" --value \"...\"\n\n# Search for patterns across all workers\nnpx claude-flow@v3alpha memory search --namespace collaboration --query \"authentication patterns\"\n\n# Retrieve specific findings\nnpx claude-flow@v3alpha memory retrieve --namespace collaboration --key \"security-findings\"\n```\n\n### Cross-Platform Learning\n\nBoth platforms learn from each other's outputs:\n\n```bash\n# After successful collaboration, train patterns\nnpx claude-flow@v3alpha hooks post-task --task-id \"dual-[id]\" --success true --train-neural true\n\n# Store successful collaboration patterns\nnpx claude-flow@v3alpha memory store --namespace patterns --key \"dual-mode-[pattern]\" --value \"[what worked]\"\n\n# Transfer learnings to both platforms\nnpx claude-flow@v3alpha hooks transfer store --pattern \"dual-collab-success\"\n```\n\n### Worker Dependency Levels\n\nWorkers execute in dependency order:\n\n```\nLevel 0: [🔵 Architect]           # No dependencies - runs first\nLevel 1: [🟢 Coder, 🔵 Tester]    # Depends on Architect\nLevel 2: [🔵 Reviewer]            # Depends on Coder + Tester\nLevel 3: [🟢 Optimizer]           # Depends on Reviewer approval\n```\n\n### Platform Strengths\n\n| Task Type | Preferred Platform | Reason |\n|-----------|-------------------|--------|\n| Architecture & Design | 🔵 Claude | Strong reasoning, system thinking |\n| Implementation | 🟢 Codex | Fast code generation |\n| Security Review | 🔵 Claude | Careful analysis, threat modeling |\n| Performance Optimization | 🟢 Codex | Code-level optimizations |\n| Testing Strategy | 🔵 Claude | Coverage analysis, edge cases |\n| Refactoring | 🟢 Codex | Bulk code transformations |\n\n### Programmatic API\n\n```typescript\nimport { DualModeOrchestrator, CollaborationTemplates } from '@claude-flow/codex';\n\nconst orchestrator = new DualModeOrchestrator({\n  namespace: 'my-feature',\n  memoryBackend: 'hybrid'\n});\n\n// Use pre-built template\nconst workers = CollaborationTemplates.featureDevelopment('Add OAuth login');\n\n// Run collaboration\nconst results = await orchestrator.runCollaboration(workers, 'Implement OAuth feature');\n\n// Access shared memory\nconst designDocs = await orchestrator.getMemory('design-decisions');\n```\n\n---\n\n## Swarm Protocols & Routing\n\n### Auto-Start Swarm Protocol\n\nWhen the user requests a complex task (multi-file changes, feature implementation, refactoring), **immediately execute this pattern in a SINGLE message:**\n\n```javascript\n// STEP 1: Initialize swarm coordination via MCP\nmcp__ruv-swarm__swarm_init({\n  topology: \"hierarchical\",\n  maxAgents: 8,\n  strategy: \"specialized\"\n})\n\n// STEP 2: Spawn NAMED agents concurrently — all in ONE message\n// Each agent knows WHO to message next in the pipeline\nTask({\n  prompt: \"Research requirements and codebase. SendMessage findings to 'architect' when done.\",\n  subagent_type: \"researcher\", name: \"researcher\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for research from 'researcher'. Design implementation. SendMessage design to 'coder'.\",\n  subagent_type: \"system-architect\", name: \"architect\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for design from 'architect'. Implement the solution. SendMessage code paths to 'tester'.\",\n  subagent_type: \"coder\", name: \"coder\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for implementation from 'coder'. Write tests. SendMessage results to 'reviewer'.\",\n  subagent_type: \"tester\", name: \"tester\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for test results from 'tester'. Review code quality and security. Report findings.\",\n  subagent_type: \"reviewer\", name: \"reviewer\", run_in_background: true\n})\n\n// STEP 3: Kick off the pipeline\nSendMessage({ to: \"researcher\", summary: \"Start research\", message: \"[task description and context]\" })\n\n// STEP 4: Batch todos\nTodoWrite({ todos: [\n  {content: \"Research and analyze requirements\", status: \"in_progress\", activeForm: \"Researching\"},\n  {content: \"Design architecture\", status: \"pending\", activeForm: \"Designing\"},\n  {content: \"Implement solution\", status: \"pending\", activeForm: \"Implementing\"},\n  {content: \"Write tests\", status: \"pending\", activeForm: \"Testing\"},\n  {content: \"Review and finalize\", status: \"pending\", activeForm: \"Reviewing\"}\n]})\n\n// Pipeline flow via SendMessage:\n// researcher ──→ architect ──→ coder ──→ tester ──→ reviewer\n```\n\n### Agent Routing (Anti-Drift)\n\n| Code | Task | Agents |\n|------|------|--------|\n| 1 | Bug Fix | coordinator, researcher, coder, tester |\n| 3 | Feature | coordinator, architect, coder, tester, reviewer |\n| 5 | Refactor | coordinator, architect, coder, reviewer |\n| 7 | Performance | coordinator, perf-engineer, coder |\n| 9 | Security | coordinator, security-architect, auditor |\n| 11 | Memory | coordinator, memory-specialist, perf-engineer |\n| 13 | Docs | researcher, api-docs |\n\n**Codes 1-11: hierarchical/specialized (anti-drift). Code 13: mesh/balanced**\n\n### Task Complexity Detection\n\n**AUTO-INVOKE SWARM when task involves:**\n- Multiple files (3+)\n- New feature implementation\n- Refactoring across modules\n- API changes with tests\n- Security-related changes\n- Performance optimization\n- Database schema changes\n\n**SKIP SWARM for:**\n- Single file edits\n- Simple bug fixes (1-2 lines)\n- Documentation updates\n- Configuration changes\n- Quick questions/exploration\n\n## Project Configuration\n\nThis project is configured with Claude Flow V3 (Anti-Drift Defaults):\n- **Topology**: hierarchical (prevents drift via central coordination)\n- **Max Agents**: 8 (smaller team = less drift)\n- **Strategy**: specialized (clear roles, no overlap)\n- **Consensus**: raft (leader maintains authoritative state)\n- **Memory Backend**: hybrid (SQLite + AgentDB)\n- **HNSW Indexing**: Enabled (measured ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force; ANN wins above the crossover)\n- **Neural Learning**: Enabled (SONA)\n\n## V3 CLI Commands (26 Commands, 140+ Subcommands)\n\n### Core Commands\n\n| Command | Subcommands | Description |\n|---------|-------------|-------------|\n| `init` | 4 | Project initialization with wizard, presets, skills, hooks |\n| `agent` | 8 | Agent lifecycle (spawn, list, status, stop, metrics, pool, health, logs) |\n| `swarm` | 6 | Multi-agent swarm coordination and orchestration |\n| `memory` | 11 | AgentDB memory with HNSW vector search (measured ~1.9x–4.7x vs brute force above crossover) |\n| `mcp` | 9 | MCP server management and tool execution |\n| `task` | 6 | Task creation, assignment, and lifecycle |\n| `session` | 7 | Session state management and persistence |\n| `config` | 7 | Configuration management and provider setup |\n| `status` | 3 | System status monitoring with watch mode |\n| `start` | 3 | Service startup and quick launch |\n| `workflow` | 6 | Workflow execution and template management |\n| `hooks` | 17 | Self-learning hooks + 12 background workers |\n| `hive-mind` | 6 | Queen-led Byzantine fault-tolerant consensus |\n\n### Advanced Commands\n\n| Command | Subcommands | Description |\n|---------|-------------|-------------|\n| `daemon` | 5 | Background worker daemon (start, stop, status, trigger, enable) |\n| `neural` | 5 | Neural pattern training (train, status, patterns, predict, optimize) |\n| `security` | 6 | Security scanning (scan, audit, cve, threats, validate, report) |\n| `performance` | 5 | Performance profiling (benchmark, profile, metrics, optimize, report) |\n| `providers` | 5 | AI providers (list, add, remove, test, configure) |\n| `plugins` | 5 | Plugin management (list, install, uninstall, enable, disable) |\n| `deployment` | 5 | Deployment management (deploy, rollback, status, environments, release) |\n| `embeddings` | 4 | Vector embeddings (embed, batch, search, init) — agentic-flow ONNX backend (speedup unverified, no benchmark) |\n| `claims` | 4 | Claims-based authorization (check, grant, revoke, list) |\n| `migrate` | 5 | V2 to V3 migration with rollback support |\n| `process` | 4 | Background process management |\n| `doctor` | 1 | System diagnostics with health checks |\n| `completions` | 4 | Shell completions (bash, zsh, fish, powershell) |\n\n### Quick CLI Examples\n\n```bash\n# Initialize project\nnpx claude-flow@v3alpha init --wizard\n\n# Start daemon with background workers\nnpx claude-flow@v3alpha daemon start\n\n# Spawn an agent\nnpx claude-flow@v3alpha agent spawn -t coder --name my-coder\n\n# Initialize swarm\nnpx claude-flow@v3alpha swarm init --v3-mode\n\n# Search memory (HNSW-indexed)\nnpx claude-flow@v3alpha memory search -q \"authentication patterns\"\n\n# System diagnostics\nnpx claude-flow@v3alpha doctor --fix\n\n# Security scan\nnpx claude-flow@v3alpha security scan --depth full\n\n# Performance benchmark\nnpx claude-flow@v3alpha performance benchmark --suite all\n```\n\n## Headless Background Instances (claude -p)\n\nUse `claude -p` (print/pipe mode) to spawn headless Claude instances for parallel background work. These run non-interactively and return results to stdout.\n\n### Basic Usage\n\n```bash\n# Single headless task\nclaude -p \"Analyze the authentication module for security issues\"\n\n# With model selection\nclaude -p --model haiku \"Format this config file\"\nclaude -p --model opus \"Design the database schema for user management\"\n\n# With output format\nclaude -p --output-format json \"List all TODO comments in src/\"\nclaude -p --output-format stream-json \"Refactor the error handling in api.ts\"\n\n# With budget limits\nclaude -p --max-budget-usd 0.50 \"Run comprehensive security audit\"\n\n# With specific tools allowed\nclaude -p --allowedTools \"Read,Grep,Glob\" \"Find all files that import the auth module\"\n\n# Skip permissions (sandboxed environments only)\nclaude -p --dangerously-skip-permissions \"Fix all lint errors in src/\"\n```\n\n### Parallel Background Execution\n\n```bash\n# Spawn multiple headless instances in parallel\nclaude -p \"Analyze src/auth/ for vulnerabilities\" &\nclaude -p \"Write tests for src/api/endpoints.ts\" &\nclaude -p \"Review src/models/ for performance issues\" &\nwait  # Wait for all to complete\n\n# With results captured\nSECURITY=$(claude -p \"Security audit of auth module\" &)\nTESTS=$(claude -p \"Generate test coverage report\" &)\nPERF=$(claude -p \"Profile memory usage in workers\" &)\nwait\necho \"$SECURITY\" \"$TESTS\" \"$PERF\"\n```\n\n### Session Continuation\n\n```bash\n# Start a task, resume later\nclaude -p --session-id \"abc-123\" \"Start analyzing the codebase\"\nclaude -p --resume \"abc-123\" \"Continue with the test files\"\n\n# Fork a session for parallel exploration\nclaude -p --resume \"abc-123\" --fork-session \"Try approach A: event sourcing\"\nclaude -p --resume \"abc-123\" --fork-session \"Try approach B: CQRS pattern\"\n```\n\n### Key Flags\n\n| Flag | Purpose |\n|------|---------|\n| `-p, --print` | Non-interactive mode, print and exit |\n| `--model <model>` | Select model (haiku, sonnet, opus) |\n| `--output-format <fmt>` | Output: text, json, stream-json |\n| `--max-budget-usd <amt>` | Spending cap per invocation |\n| `--allowedTools <tools>` | Restrict available tools |\n| `--append-system-prompt` | Add custom instructions |\n| `--resume <id>` | Continue a previous session |\n| `--fork-session` | Branch from resumed session |\n| `--fallback-model <model>` | Auto-fallback if primary overloaded |\n| `--permission-mode <mode>` | acceptEdits, bypassPermissions, plan, etc. |\n| `--mcp-config <json>` | Load MCP servers from JSON |\n\n## Available Agents (60+ Types)\n\n### Core Development\n`coder`, `reviewer`, `tester`, `planner`, `researcher`\n\n### V3 Specialized Agents\n`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`\n\n### @claude-flow/security Module\nCVE remediation, input validation, path security:\n- `InputValidator` — Zod-based validation at boundaries\n- `PathValidator` — Path traversal prevention\n- `SafeExecutor` — Command injection protection\n- `PasswordHasher` — bcrypt hashing\n- `TokenGenerator` — Secure token generation\n\n### Token Optimizer (Agent Booster)\nIntegrates agentic-flow optimizations for 30-50% token reduction:\n```typescript\nimport { getTokenOptimizer } from '@claude-flow/integration';\nconst optimizer = await getTokenOptimizer();\n\n// Compact context (32% fewer tokens)\nconst ctx = await optimizer.getCompactContext(\"auth patterns\");\n\n// 352x faster edits = fewer retries\nawait optimizer.optimizedEdit(file, old, new, \"typescript\");\n\n// Optimal config (100% success rate)\nconst config = optimizer.getOptimalConfig(agentCount);\n```\n| Feature | Token Savings |\n|---------|---------------|\n| ReasoningBank retrieval | -32% |\n| Agent Booster edits | -15% |\n| Cache (95% hit rate) | -10% |\n| Optimal batch size | -20% |\n\n### Swarm Coordination\n`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`, `collective-intelligence-coordinator`, `swarm-memory-manager`\n\n### Consensus & Distributed\n`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`, `consensus-builder`, `crdt-synchronizer`, `quorum-manager`, `security-manager`\n\n### Performance & Optimization\n`perf-analyzer`, `performance-benchmarker`, `task-orchestrator`, `memory-coordinator`, `smart-agent`\n\n### GitHub & Repository\n`github-modes`, `pr-manager`, `code-review-swarm`, `issue-tracker`, `release-manager`, `workflow-automation`, `project-board-sync`, `repo-architect`, `multi-repo-swarm`\n\n### SPARC Methodology\n`sparc-coord`, `sparc-coder`, `specification`, `pseudocode`, `architecture`, `refinement`\n\n### Specialized Development\n`backend-dev`, `mobile-dev`, `ml-developer`, `cicd-engineer`, `api-docs`, `system-architect`, `code-analyzer`, `base-template-generator`\n\n### Testing & Validation\n`tdd-london-swarm`, `production-validator`\n\n## Agent Teams & Comms System\n\nAgent 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.\n\n### Architecture\n\n```\nTeam Lead (you)\n  ├── SendMessage ←→ architect (named agent)\n  ├── SendMessage ←→ developer (named agent)\n  ├── SendMessage ←→ tester (named agent)\n  └── SendMessage ←→ reviewer (named agent)\n       ↕ agents can message each other by name\n```\n\n### Core Principle: Named Agents + SendMessage\n\nEvery agent MUST have a `name` so it's addressable. Communication happens via `SendMessage`, not polling or shared memory.\n\n```javascript\n// STEP 1: Spawn named agents (all in ONE message, background)\nTask({\n  prompt: \"Design the API. When done, send your design to 'developer' via SendMessage.\",\n  subagent_type: \"system-architect\",\n  name: \"architect\",\n  run_in_background: true\n})\nTask({\n  prompt: \"Wait for architect's design via SendMessage. Then implement it. Send code to 'tester'.\",\n  subagent_type: \"coder\",\n  name: \"developer\",\n  run_in_background: true\n})\nTask({\n  prompt: \"Wait for developer's code via SendMessage. Write tests. Send results to 'reviewer'.\",\n  subagent_type: \"tester\",\n  name: \"tester\",\n  run_in_background: true\n})\n\n// STEP 2: Kick off the pipeline by messaging the first agent\nSendMessage({\n  to: \"architect\",\n  summary: \"Start API design\",\n  message: \"Design a REST API for user management with CRUD endpoints. Send the design to 'developer' when done.\"\n})\n```\n\n### SendMessage Protocol\n\n```javascript\n// Lead → Teammate: assign work\nSendMessage({ to: \"developer\", summary: \"Implement auth\", message: \"Build OAuth2 flow...\" })\n\n// Lead → Teammate: redirect priorities\nSendMessage({ to: \"developer\", summary: \"Prioritize auth\", message: \"Auth endpoint is blocking tester, do it first.\" })\n\n// Lead → Teammate: provide context from another agent's results\nSendMessage({ to: \"tester\", summary: \"Architect output\", message: \"The architect designed these endpoints: [details]. Write tests for them.\" })\n\n// Lead → Teammate: graceful shutdown\nSendMessage({ to: \"developer\", message: { type: \"shutdown_request\" } })\n```\n\n### Coordination Patterns\n\n**Pipeline (A → B → C)** — each agent messages the next when done:\n```\narchitect ──SendMessage──→ developer ──SendMessage──→ tester ──SendMessage──→ reviewer\n```\nTell each agent WHO to message next in their prompt.\n\n**Fan-out / Fan-in** — lead spawns parallel agents, collects results:\n```\n         ┌→ researcher-1 ──→┐\nlead ────┼→ researcher-2 ──→├──→ lead synthesizes\n         └→ researcher-3 ──→┘\n```\nSpawn with `run_in_background: true`. Results arrive as task completions.\n\n**Supervisor / Worker** — lead assigns, workers report back:\n```\nlead ←──SendMessage──→ worker-1\nlead ←──SendMessage──→ worker-2\nlead ←──SendMessage──→ worker-3\n```\nLead sends tasks via SendMessage, workers respond with results.\n\n### Agent Prompt Template (Comms-Aware)\n\nWhen spawning agents that need to coordinate, include comms instructions:\n\n```javascript\nTask({\n  prompt: `You are the architect for this feature team.\n\nYOUR TASK: Design the database schema for user management.\n\nCOMMS PROTOCOL:\n- When your design is ready, send it to \"developer\" via SendMessage\n- If you need clarification, message the team lead (just output text)\n- Include file paths and key decisions in your message\n\nDELIVERABLE: Schema design with entity relationships, indexes, and migration plan.`,\n  subagent_type: \"system-architect\",\n  name: \"architect\",\n  run_in_background: true\n})\n```\n\n### Full Team Spawn Example\n\n```javascript\n// Create shared task list first\nTaskCreate({ subject: \"Design schema\", description: \"...\", activeForm: \"Designing\" })\nTaskCreate({ subject: \"Implement models\", description: \"...\", activeForm: \"Implementing\" })\nTaskCreate({ subject: \"Write tests\", description: \"...\", activeForm: \"Testing\" })\nTaskCreate({ subject: \"Security review\", description: \"...\", activeForm: \"Reviewing\" })\n\n// Spawn ALL named agents in ONE message\nTask({\n  prompt: \"Design the schema. SendMessage to 'developer' with your design when done. Update task #1.\",\n  subagent_type: \"system-architect\", name: \"architect\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for schema from 'architect'. Implement models + endpoints. SendMessage to 'tester'. Update task #2.\",\n  subagent_type: \"coder\", name: \"developer\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for code from 'developer'. Write integration tests. SendMessage results to 'security'. Update task #3.\",\n  subagent_type: \"tester\", name: \"tester\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for test results from 'tester'. Review for vulnerabilities. Update task #4.\",\n  subagent_type: \"security-auditor\", name: \"security\", run_in_background: true\n})\n```\n\n### Agent Teams Hooks\n\n| Hook | Trigger | Purpose |\n|------|---------|---------|\n| `TeammateIdle` | Teammate finishes turn | Auto-assign pending tasks via SendMessage |\n| `TaskCompleted` | Task marked complete | Train patterns, notify lead via SendMessage |\n\n```bash\nnpx claude-flow@v3alpha hooks teammate-idle --auto-assign true\nnpx claude-flow@v3alpha hooks task-completed -i task-123 --train-patterns true\n```\n\n### Rules\n\n1. **Always name agents** — use `name: \"role-name\"` so they're addressable\n2. **Comms over memory** — use SendMessage for real-time coordination, memory for persistence\n3. **Pipeline prompts** — tell each agent WHO to message next and WHAT to send\n4. **Spawn all at once** — all Task calls in ONE message with `run_in_background: true`\n5. **Don't poll** — agents message back when done; wait for task completion notifications\n6. **Graceful shutdown** — send `{ type: \"shutdown_request\" }` before TeamDelete\n7. **Lead synthesizes** — when agents complete, review ALL results before responding to user\n\n## V3 Hooks System (17 Hooks + 12 Workers)\n\n### Hook Categories\n\n| Category | Hooks | Purpose |\n|----------|-------|---------|\n| **Core** | `pre-edit`, `post-edit`, `pre-command`, `post-command`, `pre-task`, `post-task` | Tool lifecycle |\n| **Session** | `session-start`, `session-end`, `session-restore`, `notify` | Context management |\n| **Intelligence** | `route`, `explain`, `pretrain`, `build-agents`, `transfer` | Neural learning |\n| **Learning** | `intelligence` (trajectory-start/step/end, pattern-store/search, stats, attention) | Reinforcement |\n| **Agent Teams** | `teammate-idle`, `task-completed` | Multi-agent coordination |\n\n### 12 Background Workers\n\n| Worker | Priority | Description |\n|--------|----------|-------------|\n| `ultralearn` | normal | Deep knowledge acquisition |\n| `optimize` | high | Performance optimization |\n| `consolidate` | low | Memory consolidation |\n| `predict` | normal | Predictive preloading |\n| `audit` | critical | Security analysis |\n| `map` | normal | Codebase mapping |\n| `preload` | low | Resource preloading |\n| `deepdive` | normal | Deep code analysis |\n| `document` | normal | Auto-documentation |\n| `refactor` | normal | Refactoring suggestions |\n| `benchmark` | normal | Performance benchmarking |\n| `testgaps` | normal | Test coverage analysis |\n\n### Essential Hook Commands\n\n```bash\n# Core hooks\nnpx claude-flow@v3alpha hooks pre-task --description \"[task]\"\nnpx claude-flow@v3alpha hooks post-task --task-id \"[id]\" --success true\nnpx claude-flow@v3alpha hooks post-edit --file \"[file]\" --train-patterns\n\n# Session management\nnpx claude-flow@v3alpha hooks session-start --session-id \"[id]\"\nnpx claude-flow@v3alpha hooks session-end --export-metrics true\nnpx claude-flow@v3alpha hooks session-restore --session-id \"[id]\"\n\n# Intelligence routing\nnpx claude-flow@v3alpha hooks route --task \"[task]\"\nnpx claude-flow@v3alpha hooks explain --topic \"[topic]\"\n\n# Neural learning\nnpx claude-flow@v3alpha hooks pretrain --model-type moe --epochs 10\nnpx claude-flow@v3alpha hooks build-agents --agent-types coder,tester\n\n# Background workers\nnpx claude-flow@v3alpha hooks worker list\nnpx claude-flow@v3alpha hooks worker dispatch --trigger audit\nnpx claude-flow@v3alpha hooks worker status\n```\n\n## Intelligence System (RuVector)\n\nV3 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)):\n- **SONA**: Self-Optimizing Neural Architecture (measured 0.0043ms/adapt, target <0.05ms met)\n- **MoE**: Mixture of Experts for specialized routing (gate converges — confidence 0.13→0.88 after rewards)\n- **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)\n- **EWC++**: Elastic Weight Consolidation (prevents forgetting)\n- **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)\n\nThe 4-step intelligence pipeline:\n1. **RETRIEVE** — Fetch relevant patterns via HNSW\n2. **JUDGE** — Evaluate with verdicts (success/failure)\n3. **DISTILL** — Extract key learnings via LoRA\n4. **CONSOLIDATE** — Prevent catastrophic forgetting via EWC++\n\n## Embeddings Package (v3.0.0-alpha.12)\n\nFeatures:\n- **sql.js**: Cross-platform SQLite persistent cache (WASM, no native compilation)\n- **Document chunking**: Configurable overlap and size\n- **Normalization**: L2, L1, min-max, z-score\n- **Hyperbolic embeddings**: Poincare ball model for hierarchical data\n- **agentic-flow ONNX integration**: speedup unverified (no benchmark; backend reported `onnx`, model all-MiniLM-L6-v2, 384-dim)\n- **Neural substrate**: Integration with RuVector\n\n## Hive-Mind Consensus\n\n### Topologies\n- `hierarchical` — Queen controls workers directly\n- `mesh` — Fully connected peer network\n- `hierarchical-mesh` — Hybrid (recommended)\n- `adaptive` — Dynamic based on load\n\n### Consensus Strategies\n- `byzantine` — BFT (tolerates f < n/3 faulty)\n- `raft` — Leader-based (tolerates f < n/2)\n- `gossip` — Epidemic for eventual consistency\n- `crdt` — Conflict-free replicated data types\n- `quorum` — Configurable quorum-based\n\n## V3 Performance Targets\n\n> 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\".\n\n| Metric | Measured / Target | Status |\n|--------|-------------------|--------|\n| 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) |\n| Int8 Quantization | 3.84x compression, reconstruction cosine 0.99999 | **Measured** |\n| RaBitQ Quantization | 32x compression, 0.60ms/query (14,760-vec index) | **Measured** |\n| SONA Adaptation | 0.0043ms/adapt (target <0.05ms met) | **Measured** |\n| MoE Gate | converges — confidence 0.13→0.88, Q 0→99.8 after rewards | **Measured** |\n| 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 |\n| MCP Response | <100ms | target |\n| CLI Startup | <500ms | target |\n\n## Environment Variables\n\n```bash\n# Configuration\nCLAUDE_FLOW_CONFIG=./claude-flow.config.json\nCLAUDE_FLOW_LOG_LEVEL=info\n\n# Provider API Keys\nANTHROPIC_API_KEY=sk-ant-...\nOPENAI_API_KEY=sk-...\nGOOGLE_API_KEY=...\n\n# MCP Server\nCLAUDE_FLOW_MCP_PORT=3000\nCLAUDE_FLOW_MCP_HOST=localhost\nCLAUDE_FLOW_MCP_TRANSPORT=stdio\n\n# Memory\nCLAUDE_FLOW_MEMORY_BACKEND=hybrid\nCLAUDE_FLOW_MEMORY_PATH=./data/memory\n```\n\n## Doctor Health Checks\n\nRun `npx claude-flow@v3alpha doctor` to check:\n- Node.js version (20+)\n- npm version (9+)\n- Git installation\n- Config file validity\n- Daemon status\n- Memory database\n- API keys\n- MCP servers\n- Disk space\n- TypeScript installation\n\n## Quick Setup\n\n```bash\n# Add MCP servers\nclaude mcp add claude-flow -- npx -y ruflo@latest mcp start\nclaude mcp add ruv-swarm npx ruv-swarm mcp start  # Optional\nclaude mcp add flow-nexus npx flow-nexus@latest mcp start  # Optional\n\n# Start daemon\nnpx claude-flow@v3alpha daemon start\n\n# Run doctor\nnpx claude-flow@v3alpha doctor --fix\n```\n\n## Claude Code vs MCP Tools\n\n### Claude Code Handles ALL EXECUTION:\n- **Task tool**: Spawn and run agents concurrently\n- File operations (Read, Write, Edit, MultiEdit, Glob, Grep)\n- Code generation and programming\n- Bash commands and system operations\n- TodoWrite and task management\n- Git operations\n\n### MCP Tools ONLY COORDINATE:\n- Swarm initialization (topology setup)\n- Agent type definitions\n- Task orchestration\n- Memory management\n- Neural features\n- Performance tracking\n\n- Keep MCP for coordination strategy only — use Claude Code's Task tool for real execution\n\n## Claude Code ↔ AgentDB Memory Bridge\n\nClaude Code's auto-memory (`~/.claude/projects/*/memory/*.md`) is bridged to AgentDB with ONNX vector embeddings for semantic search.\n\n### MCP Tools\n\n| Tool | Description |\n|------|-------------|\n| `memory_import_claude` | Import Claude Code memories into AgentDB with 384-dim ONNX embeddings. Use `allProjects: true` to import from ALL projects. |\n| `memory_bridge_status` | Show bridge health — Claude files, AgentDB entries, SONA state, connection status |\n| `memory_search_unified` | Semantic search across ALL namespaces (claude-memories, auto-memory, patterns, tasks, feedback) |\n\n### Auto-Import on Session Start\n\nThe `SessionStart` hook automatically imports current project's memories into AgentDB. For manual import of all projects:\n\n```bash\n# Via MCP tool (from Claude Code)\nmemory_import_claude({ allProjects: true })\n\n# Via helper hook (from terminal)\nnode .claude/helpers/auto-memory-hook.mjs import-all\n```\n\n### Unified Search\n\nSearch across both Claude Code memories and AgentDB entries:\n\n```bash\n# Via MCP tool\nmemory_search_unified({ query: \"authentication security\", limit: 5 })\n\n# Results include source attribution: claude-code, auto-memory, or agentdb\n```\n\n### Intelligence Pipeline\n\n| Component | Status | Details |\n|-----------|--------|---------|\n| ONNX Embeddings | Active | all-MiniLM-L6-v2, 384 dimensions |\n| SONA Learning | Active | Pattern matching + trajectory recording |\n| ReasoningBank | Active | Pattern storage with file persistence |\n| AgentDB sql.js | Active | SQLite with vector_indexes table |\n\n## Publishing to npm\n\n### Versioning policy (stable releases — alpha series ended at 3.7.0-alpha.81, 2026-05-23)\n\n- **From 3.7.0 onward we ship stable semver**, NOT alpha pre-releases.\n- Bump rules (semver discipline):\n  - **PATCH** (3.7.0 → 3.7.1): bug fixes only, no API change, no schema change\n  - **MINOR** (3.7.0 → 3.8.0): backward-compatible additions (new MCP tool, new flag, new agent type)\n  - **MAJOR** (3.x → 4.0.0): breaking change in CLI surface, MCP tool signature, file layout, or default behavior\n- 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`.\n- Never publish a pre-release (`-alpha.N`, `-beta.N`, `-rc.N`) unless the user explicitly asks for a pre-release flow.\n\n### Publishing Rules\n\n- The normal public release train is exactly THREE packages:\n  `@claude-flow/cli`, `claude-flow`, and `ruflo`.\n- Internal `@claude-flow/*` components are bundled into the public artifacts;\n  do not publish them standalone as part of the normal release.\n- MUST update ALL dist-tags for ALL THREE packages after publishing (latest + alpha + v3alpha all point to the same version)\n- Publish order: `@claude-flow/cli` first, then `claude-flow` (umbrella), then `ruflo` (alias umbrella)\n- MUST run verification for ALL THREE before telling user publishing is complete\n- Run `node scripts/audit-umbrella-version-lockstep.mjs` before packing or\n  publishing.\n- Publish from a clean reviewed commit/tag-equivalent worktree. Do not ship\n  unrelated uncommitted changes.\n- A fresh worktree has two separate dependency trees to install before anything\n  builds: `npm install` at repo root (npm workspaces), AND `pnpm install` inside\n  `v3/` (a separate pnpm workspace — root `prepare-root-publish.mjs` shells out to\n  `pnpm --filter` to build `v3/@claude-flow/{shared,hooks,guidance}`, which fails\n  with `spawn ENOENT` on `tsc` if `v3/node_modules` was never populated).\n- Use the existing authenticated `ruvnet` npm session. Do not replace it with a\n  token from another GCP project.\n\n**`npm publish` auth — FIXED (2026-07-30):** use the `NPM_TOKEN` secret directly,\nvia a throwaway `.npmrc` with `NPM_CONFIG_USERCONFIG` — same pattern as the\nhelpers-signing-key handling. It is mirrored in two GCP projects — `ruv-dev`\n(version 3+) and `cognitum-20260110` (version 7+) — so either project's copy\nis current; use whichever `gcloud` session is already authenticated. This is a\ngranular access token (\"ruflo publishjing\", expires 2026-10-28) with\n`package: write` + `bypass_2fa: true`, scoped broadly enough to cover\n`@claude-flow/cli`, `claude-flow`, and `ruflo` (plus the `cognitum`/\n`cognitum-one` orgs). Confirmed end-to-end against the real registry (not just\na permissions probe): `npm publish` for `@claude-flow/cli` succeeded via this\ntoken with zero OTP/WebAuthn prompt, and\n`npm dist-tag add` against both a scoped (`@claude-flow/cli`) and unscoped\n(`claude-flow`) package also went through with no prompt.\n\n**Why the earlier `NPM_TOKEN` version failed:** versions 1/2 of that secret\nwere older classic automation tokens, and npm has been restricting tokens that\nbypass 2FA for writes account-wide (the login flow prints this notice —\n`gh.io/npm-gat-bypass2fa-deprecation`). Version 3 is a **granular access\ntoken** created explicitly for this purpose, which is npm's supported\nreplacement path (its own 2FA-bypass flag still works for a granular token,\nunlike the deprecated classic automation tokens). If this token's `bypass_2fa`\nflag or scope ever gets narrowed/expired (check expiry above), the fallback\nis the WebAuthn dance below — but try this path first every time.\n\n```bash\ngcloud secrets versions access latest --secret=NPM_TOKEN --project=ruv-dev > /tmp/.npmrc-publish-raw\nprintf '//registry.npmjs.org/:_authToken=%s\\n' \"$(cat /tmp/.npmrc-publish-raw)\" > /tmp/.npmrc-publish\nrm -f /tmp/.npmrc-publish-raw\nNPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm publish   # from the package dir, with signing-key env vars for @claude-flow/cli\nNPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> alpha\nNPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> v3alpha\nshred -u /tmp/.npmrc-publish 2>/dev/null || rm -f /tmp/.npmrc-publish   # ALWAYS clean up, same discipline as the signing key\n```\n\n**Fallback — WebAuthn procedure, if the token above is dead:** the `ruvnet`\naccount's 2FA method is a WebAuthn security key, not TOTP (no numeric\n`--otp=<code>` exists). This must be driven by the human (an agent cannot\napprove a WebAuthn browser prompt):\n1. Human goes to npmjs.com → account 2FA settings → turns OFF \"Require\n   two-factor authentication for write actions\" (narrows to auth-only, not a\n   full 2FA disable), then runs `npm login` in their own terminal to refresh\n   the session under the new setting.\n2. Agent can then run `npm publish` directly via Bash with no further prompt.\n3. **`npm dist-tag add` still requires a fresh WebAuthn approval PER CALL**\n   regardless of the write-2FA setting — 6 individual browser approvals for a\n   3-package release (alpha + v3alpha × 3), not 1. Tell the human up front.\n- After every dist-tag call (or if unsure), verify with\n  `npm view <pkg> dist-tags --json` — don't trust the CLI's own stdout alone, since\n  a WebAuthn prompt that's still pending in the browser produces no terminal\n  output an agent can see.\n- Confirm the version actually landed (`npm view <pkg>@<version> version`) before\n  telling the user publishing succeeded, same reasoning: a mid-publish approval\n  that never gets answered fails silently from an agent's point of view.\n\n**Helpers signing key (required for `@claude-flow/cli` publish):** `npm publish`'s\n`prepublishOnly` runs `scripts/sign-helpers.mjs`, which needs a private key to sign\n`.claude/helpers/helpers.manifest.json`. The secret lives in GCP Secret Manager in the\n**`ruv-dev`** project (not `cognitum-20260110` or `claude-flow` — checked both, not there),\nsecret name `ruflo-helpers-signing-key`:\n\n```bash\ncd v3/@claude-flow/cli\nRUFLO_HELPERS_SIGNING_SECRET=ruflo-helpers-signing-key RUFLO_HELPERS_SIGNING_PROJECT=ruv-dev \\\n  npm publish\n```\n\n(`ruv-dev` also holds `ruflo-config-signing-key`; do not replace the existing\nauthenticated npm session with a token from another project.)\n\n**Handling the signing key without leaking it (learned 2026-07-14, hard way):**\nan earlier Windows path invoked `gcloud` without its required `.cmd` suffix. The\nfallback command printed the PEM into captured tool output and a session transcript.\nGCP secret v1 was destroyed and a fresh v2 was rotated in (commit 0052b1b06 /\nPR #2673). `sign-helpers.mjs` now selects `gcloud.cmd` on Windows and supports a\nstdin-only fallback. **Rules:**\n- NEVER invoke `gcloud secrets versions access` in a way that lets the payload reach\n  tool output. Use the built-in `RUFLO_HELPERS_SIGNING_SECRET` path above, or pipe\n  directly into the signer:\n  `gcloud secrets versions access latest --secret=ruflo-helpers-signing-key --project=ruv-dev | node scripts/sign-helpers.mjs --stdin-key`.\n- `--stdin-key` refuses interactive entry, validates Ed25519 key type, and never\n  echoes parser input. A local file via `RUFLO_HELPERS_SIGNING_KEY` remains the\n  air-gapped fallback.\n- If a rotation IS needed, keep the private half in `~/.ruflo/helpers-signing.key`\n  only, print ONLY the public half (via `Ed25519 pub export` from Node crypto), upload\n  new private via `gcloud secrets versions add … --data-file=`, then\n  `gcloud secrets versions destroy <old>` to make the old irrecoverable.\n\n**Windows `prepublishOnly` failure (learned 2026-07-14):** the CLI's `prepublishOnly`\nchain (`cp ../../../README.md ./README.md && rm -rf plugins && mkdir -p plugins && cp -r ...`)\nis POSIX-shell-only. On Windows, npm runs it via `cmd.exe /d /s /c` which chokes on\n`mkdir -p` (interprets `-p` as a directory name) and `cp -r` (no such command). Two\nworkarounds until the script is rewritten in cross-platform Node:\n1. Run the prep steps manually in Git Bash, then `npm publish --ignore-scripts`.\n2. Or use a POSIX shell for the whole publish: `SHELL=bash npm publish` — but this\n   doesn't always take effect on Windows depending on npm version.\nOption 1 is what worked for v3.29.0. Track proper fix in ruvnet/ruflo issue for\ncross-platform prepublish.\n\n**Concurrent-session helper corruption (real, observed, be paranoid):** multiple Claude Code\nsessions can have their own `npm exec @claude-flow/cli@latest mcp start` MCP server running\nconcurrently with `cwd` inside this repo (check with `readlink /proc/<pid>/cwd` on\n`pgrep -f \"npm exec @claude-flow/cli@latest mcp start\"`). If one of those resolved an older\ncached `@latest` (predating the `semver.gte` downgrade-guard in\n`helper-refresh.ts:autoRefreshHelpersIfStale`), it will silently overwrite this repo's\nhand-maintained `.claude/helpers/hook-handler.cjs` / `intelligence.cjs` (root AND package\ncopies) — and `helpers.manifest.json` + `.helpers-version` — with its own older bundled\ncontent, mid-session, with no warning. Observed live 2026-07-13: this happened *twice* in\none publish flow, once right after a manual revert and once right after signing (silently\ninvalidating a freshly-signed manifest). **Mitigation:** never trust the on-disk state of\nthose files between tool calls — `git diff --stat` them immediately before any `git add`/\n`sign-helpers.mjs`/`npm publish` step, `git checkout HEAD --` revert if dirty, and chain\nrevert → sign → verify → add → commit as ONE bash invocation (`&&`-joined) to minimize the\nrace window. `npm publish`'s own `prepublishOnly` re-signs fresh at pack time regardless, so\nwhat matters is the on-disk state at the *exact moment* `npm publish` runs, not before.\n\n```bash\n# Replace 3.7.1 below with your chosen stable version (patch/minor/major per the rules above)\n\n# STEP 1: Build and publish @claude-flow/cli\ncd v3/@claude-flow/cli\nnpm version 3.7.1 --no-git-tag-version\nnpm run build\nnpm publish                              # default tag is `latest` — no --tag flag\nnpm dist-tag add @claude-flow/cli@3.7.1 alpha     # historical compat\nnpm dist-tag add @claude-flow/cli@3.7.1 v3alpha   # historical compat\n\n# STEP 2: Publish claude-flow umbrella\ncd /Users/cohen/Projects/ruflo                    # or your repo root\nnpm version 3.7.1 --no-git-tag-version\nnpm publish\nnpm dist-tag add claude-flow@3.7.1 alpha\nnpm dist-tag add claude-flow@3.7.1 v3alpha\n\n# STEP 3: Publish ruflo wrapper (CRITICAL — DON'T FORGET — this is what users run)\ncd ruflo\nnpm version 3.7.1 --no-git-tag-version\nnpm publish\nnpm dist-tag add ruflo@3.7.1 alpha\nnpm dist-tag add ruflo@3.7.1 v3alpha\n```\n\n**Verification (run before telling user publishing is complete):**\n\n```bash\nfor pkg in @claude-flow/cli claude-flow ruflo; do\n  echo \"$pkg: $(npm view $pkg@latest version)\"\n  npm view $pkg dist-tags --json\ndone\n# All three must show latest === alpha === v3alpha === new version\n```\n\n### All Tags That Must Be Updated\n\n| Package | Tag | Command Users Run |\n|---------|-----|-------------------|\n| `@claude-flow/cli` | `latest` | `npx @claude-flow/cli@latest` |\n| `@claude-flow/cli` | `alpha` | `npx @claude-flow/cli@alpha` (legacy compat) |\n| `@claude-flow/cli` | `v3alpha` | `npx @claude-flow/cli@v3alpha` (legacy compat) |\n| `claude-flow` | `latest` | `npx claude-flow@latest` |\n| `claude-flow` | `alpha` | `npx claude-flow@alpha` (legacy compat) |\n| `claude-flow` | `v3alpha` | `npx claude-flow@v3alpha` (legacy compat) |\n| `ruflo` | `latest` | `npx ruflo@latest` |\n| `ruflo` | `alpha` | `npx ruflo@alpha` (legacy compat) |\n| `ruflo` | `v3alpha` | `npx ruflo@v3alpha` (legacy compat) |\n\n- Never forget the `ruflo` package — it's the thin wrapper users actually run via `npx ruflo`\n- The legacy `alpha` and `v3alpha` tags MUST stay pointed at the latest stable so old install commands keep working\n- `ruflo` source is in `/ruflo/` — it depends on `@claude-flow/cli`\n- 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)\n\n### GitHub Release after publish\n\nEvery stable bump SHOULD have a matching `gh release create v<version>` with consolidated release notes pointing at the gist if one exists. Example:\n\n```bash\ngit tag v3.7.1 main\ngit push origin v3.7.1\ngh release create v3.7.1 --title \"v3.7.1 — <one-line headline>\" \\\n  --notes-file /tmp/release-notes.md\n```\n\n## Plugin Registry Maintenance (IPFS/Pinata)\n\nThe plugin registry is stored on IPFS via Pinata for decentralized, immutable distribution.\n\n### Registry Location\n- **Current CID**: Stored in `v3/@claude-flow/cli/src/plugins/store/discovery.ts`\n- **Gateway**: `https://gateway.pinata.cloud/ipfs/{CID}`\n- **Format**: JSON with plugin metadata, categories, featured/trending lists\n\n### Required Environment Variables\nAdd to `.env` (NEVER commit actual values):\n```bash\nPINATA_API_KEY=your-api-key\nPINATA_API_SECRET=your-api-secret\nPINATA_API_JWT=your-jwt-token\n```\n\n## Plugin Registry Operations\n\n### Adding a New Plugin to Registry\n\n1. **Fetch current registry**:\n```bash\ncurl -s \"https://gateway.pinata.cloud/ipfs/$(grep LIVE_REGISTRY_CID v3/@claude-flow/cli/src/plugins/store/discovery.ts | cut -d\"'\" -f2)\" > /tmp/registry.json\n```\n\n2. **Add plugin entry** to the `plugins` array:\n```json\n{\n  \"id\": \"@claude-flow/your-plugin\",\n  \"name\": \"@claude-flow/your-plugin\",\n  \"displayName\": \"Your Plugin\",\n  \"description\": \"Plugin description\",\n  \"version\": \"1.0.0-alpha.1\",\n  \"size\": 100000,\n  \"checksum\": \"sha256:abc123\",\n  \"author\": {\"id\": \"claude-flow-team\", \"displayName\": \"Claude Flow Team\", \"verified\": true},\n  \"license\": \"MIT\",\n  \"categories\": [\"official\"],\n  \"tags\": [\"your\", \"tags\"],\n  \"downloads\": 0,\n  \"rating\": 5,\n  \"lastUpdated\": \"2026-01-25T00:00:00.000Z\",\n  \"minClaudeFlowVersion\": \"3.0.0\",\n  \"type\": \"integration\",\n  \"hooks\": [],\n  \"commands\": [],\n  \"permissions\": [\"memory\"],\n  \"exports\": [\"YourExport\"],\n  \"verified\": true,\n  \"trustLevel\": \"official\"\n}\n```\n\n3. **Update counts and arrays**:\n   - Increment `totalPlugins`\n   - Add to `official` array\n   - Add to `featured`/`newest` if applicable\n   - Update category `pluginCount`\n\n4. **Upload to Pinata** (read credentials from .env):\n```bash\n# Source credentials from .env\nPINATA_JWT=$(grep \"^PINATA_API_JWT=\" .env | cut -d'=' -f2-)\n\n# Upload updated registry\ncurl -X POST \"https://api.pinata.cloud/pinning/pinJSONToIPFS\" \\\n  -H \"Authorization: Bearer $PINATA_JWT\" \\\n  -H \"Content-Type: application/json\" \\\n  -d @/tmp/registry.json\n```\n\n5. **Update discovery.ts** with new CID:\n```typescript\nexport const LIVE_REGISTRY_CID = 'NEW_CID_FROM_PINATA';\n```\n\n6. **Also update demo registry** in discovery.ts `demoPluginRegistry` for offline fallback\n\n### Security Rules\n- NEVER hardcode API keys in scripts or source files\n- NEVER commit .env (already in .gitignore)\n- Always source credentials from environment at runtime\n- Always delete temporary scripts after one-time uploads\n\n### Verification\n```bash\n# Verify new registry is accessible\ncurl -s \"https://gateway.pinata.cloud/ipfs/{NEW_CID}\" | jq '.totalPlugins'\n```\n\n## MetaHarness Integration (ADR-150)\n\nRuflo 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.\n\n### Architectural constraint (load-bearing)\n\n**Ruflo remains operational if every MetaHarness package is removed.** Four rules:\n1. **Removable**: `npm ls --without @metaharness/*` must still produce a working CLI\n2. **Optional in package.json**: `@metaharness/*` packages MUST be optional peers, never normal dependencies\n3. **Graceful degradation**: every code path that touches MetaHarness catches `MODULE_NOT_FOUND` and falls back\n4. **CI gate**: `.github/workflows/no-metaharness-smoke.yml` enforces all three by static grep + runtime drill on every PR\n\n### Command + tool surface\n\n```bash\n# CLI subcommands (npx ruflo metaharness …)\nnpx ruflo metaharness score                      # 5-dim readiness scorecard\nnpx ruflo metaharness genome                     # 7-section categorical report\nnpx ruflo metaharness mcp-scan --fail-on high    # static security findings\nnpx ruflo metaharness threat-model               # enterprise threat report\nnpx ruflo metaharness oia-audit --alert-on-worst high\n                                                 # composite weekly audit → memory\nnpx ruflo metaharness audit-list --since 30d     # enumerate audit records\nnpx ruflo metaharness audit-trend \\              # diff two audits (drift)\n  --baseline-key <a> --current-key <b> --alert-on-worsening \\\n  --alert-on-distance-below 0.85               # iter 38 — structural-distance gate (ADR-152 §3.1)\nnpx ruflo metaharness similarity \\               # iter 36 — ADR-152 §3.1 weighted similarity\n  --a a.json --b b.json [--per-dimension] [--alert-below 0.5]\nnpx ruflo metaharness drift-from-history \\       # iter 53 — 1-command drift (composes 3 primitives)\n  [--baseline-since 7d] [--baseline-key <key>] [--baseline-file <path>] \\\n  [--threshold 0.95] [--alert-on-new-severity high] [--dry-run]\n                                                 # iter 66 — --baseline-key skips audit-list (~14x faster)\n                                                 # iter 67 — --baseline-file skips memory entirely (~19x faster)\n                                                 # iter 78 — --alert-on-new-severity adds orthogonal finding-severity gate\nnpx ruflo metaharness mint --name foo --template vertical:coding --confirm\nnpx ruflo metaharness redblue init               # @metaharness/redblue — scaffold redblue.yaml\nnpx ruflo metaharness redblue run --mock-judge --tests 10\n                                                 # $0 marker-fixture path (CI / offline)\nnpx ruflo metaharness redblue run --tests 50 --patch\n                                                 # real model judge (needs OPENROUTER_API_KEY,\n                                                 #   capped by max_cost_usd, default $3)\nnpx ruflo metaharness redblue attack prompt --count 3\n                                                 # preview generated attack cases (no target call)\nnpx ruflo metaharness redblue patch --mock-judge # baseline → blue-team patch → retest delta\nnpx ruflo metaharness redblue report --in report.json\n                                                 # render existing report as markdown\nnpx ruflo metaharness learn --host claude-code --model haiku --slice slices/lite.json\n                                                 # metaharness@0.3.0 / upstream ADR-235 —\n                                                 #   GEPA learning run; $0 dry-run default,\n                                                 #   --run to spend; needs a metaharness\n                                                 #   repo checkout (--repo / $METAHARNESS_REPO)\nnpx ruflo metaharness gepa --op genome           # darwin@0.8.0 GEPA library — load + validate\n                                                 #   the shipped cand-6 genome (or --path <f>)\nnpx ruflo metaharness gepa --op render           # genome → the system prompt it compiles to\nnpx ruflo metaharness gepa --op analyze --transcript run.json\n                                                 # classify failure modes in a transcript\nnpx ruflo metaharness evolve --bench .harness/bench.json\n                                                 # Darwin proposes candidates; governed gates decide\nnpx ruflo metaharness bench verify --path .harness/bench.json\n                                                 # create or verify stable benchmark corpora\nnpx ruflo metaharness flywheel run --proposer auto --max-concurrency 2\n                                                 # bounded concurrent evaluation; does not promote\nnpx ruflo metaharness flywheel receipts          # inspect immutable evaluation receipts\nnpx ruflo metaharness flywheel promote <receipt-id> \\\n  --public-key ./approved-ed25519-public.pem --confirm\n                                                 # explicit policy-authorized atomic promotion\n\n# Dedicated command\nnpx ruflo eject --name my-harness                # lift ruflo project → standalone harness\n                                                 # dry-run by default; refuses in-repo target\n\n# Doctor health check\nnpx ruflo doctor --component metaharness         # report metaharness availability + version\n\n# MCP tools (callable by Claude Code agents)\nmcp__claude-flow__metaharness_score\nmcp__claude-flow__metaharness_genome\nmcp__claude-flow__metaharness_mcp_scan\nmcp__claude-flow__metaharness_threat_model\nmcp__claude-flow__metaharness_oia_audit\nmcp__claude-flow__metaharness_audit_list\nmcp__claude-flow__metaharness_audit_trend\nmcp__claude-flow__metaharness_similarity          # iter 36 — ADR-152 §3.1 genome similarity\nmcp__claude-flow__metaharness_drift_from_history  # iter 53 — 1-command drift detection\nmcp__claude-flow__metaharness_bench               # ADR-153 — create/verify bench suites for evolve --bench\nmcp__claude-flow__metaharness_evolve              # MAP-Elites driver — evolve a harness across bench suites\nmcp__claude-flow__metaharness_security_bench      # security-focused benchmark suite gate\nmcp__claude-flow__metaharness_redblue             # @metaharness/redblue — adversarial red/blue LLM testing (init|run|patch|attack|report)\nmcp__claude-flow__metaharness_learn               # metaharness@0.3.0 — GEPA learning run ($0 dry-run default; run=true to spend)\nmcp__claude-flow__metaharness_gepa                # darwin@0.8.0 — GEPA genome ops (genome|validate|render|analyze); gepaOptimize stays library-only\nmcp__claude-flow__metaharness_flywheel            # ADR-322 — evaluate concurrently, inspect receipts/ledger, or explicitly promote\n```\n\n### Routing integration (ADR-148/149)\n\n`@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.\n\n### SelfEvolvingRouter parallel-logging (ADR-150 Phase 2)\n\nWhen `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:\n\n```bash\nnode plugins/ruflo-metaharness/scripts/router-parallel-analyze.mjs \\\n  --input .swarm/router-parallel.jsonl --strict\n```\n\nThe 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.\n\n### CI workflows\n\n- `metaharness-ci.yml` — score / mcp-scan / router-compat / eject-dryrun jobs on every PR touching `plugins/ruflo-metaharness/**`\n- `no-metaharness-smoke.yml` — enforces the four architectural-constraint rules above on every PR\n- `oia-audit-weekly.yml` — Sundays 04:17 UTC, runs composite audit, uploads 90-day artifact\n\n### Cross-references\n\n- [ADR-150](v3/docs/adr/ADR-150-metaharness-integration-surfaces.md) — decision + implementation notes\n- [Issue #2399](https://github.com/ruvnet/ruflo/issues/2399) — phase tracker\n- [Research gist](https://gist.github.com/ruvnet/19d166ff9acf368c9da4172d91ac9113) — graded evidence\n- Upstream: `github.com/ruvnet/agent-harness-generator`\n\n## Optional Plugins (20 Available)\n\nPlugins are distributed via IPFS and can be installed with the CLI. Browse and install from the official registry:\n\n```bash\n# List all available plugins\nnpx claude-flow@v3alpha plugins list\n\n# Install a plugin\nnpx claude-flow@v3alpha plugins install @claude-flow/plugin-name\n\n# Enable/disable\nnpx claude-flow@v3alpha plugins enable @claude-flow/plugin-name\nnpx claude-flow@v3alpha plugins disable @claude-flow/plugin-name\n```\n\n### Core Plugins\n\n| Plugin | Version | Description |\n|--------|---------|-------------|\n| `@claude-flow/embeddings` | 3.0.0-alpha.1 | Vector embeddings with sql.js, HNSW, hyperbolic support |\n| `@claude-flow/security` | 3.0.0-alpha.1 | Input validation, path security, CVE remediation |\n| `@claude-flow/claims` | 3.0.0-alpha.8 | Claims-based authorization (check, grant, revoke, list) |\n| `@claude-flow/neural` | 3.0.0-alpha.7 | Neural pattern training (SONA, MoE, EWC++) |\n| `@claude-flow/plugins` | 3.0.0-alpha.1 | Plugin system core (manager, discovery, store) |\n| `@claude-flow/performance` | 3.0.0-alpha.1 | Performance profiling and benchmarking |\n\n### Integration Plugins\n\n| Plugin | Version | Description |\n|--------|---------|-------------|\n| `@claude-flow/plugin-agentic-qe` | 3.0.0-alpha.4 | Agentic quality engineering integration |\n| `@claude-flow/plugin-prime-radiant` | 0.1.5 | Prime Radiant intelligence integration |\n| `@claude-flow/plugin-gastown-bridge` | 3.0.0-alpha.1 | Gastown bridge protocol integration |\n| `@claude-flow/teammate-plugin` | 1.0.0-alpha.1 | Multi-agent teammate coordination |\n| `@claude-flow/plugin-code-intelligence` | 0.1.0 | Advanced code analysis and intelligence |\n| `@claude-flow/plugin-test-intelligence` | 0.1.0 | Intelligent test generation and gap analysis |\n| `@claude-flow/plugin-perf-optimizer` | 0.1.0 | Performance optimization automation |\n| `@claude-flow/plugin-neural-coordinator` | 0.1.0 | Neural network coordination across agents |\n| `@claude-flow/plugin-cognitive-kernel` | 0.1.0 | Core cognitive processing kernel |\n| `@claude-flow/plugin-quantum-optimizer` | 0.1.0 | Quantum-inspired optimization algorithms |\n| `@claude-flow/plugin-hyperbolic-reasoning` | 0.1.0 | Hyperbolic space reasoning for hierarchical data |\n\n### Domain-Specific Plugins\n\n| Plugin | Version | Description |\n|--------|---------|-------------|\n| `@claude-flow/plugin-healthcare-clinical` | 0.1.0 | Healthcare clinical workflow automation |\n| `@claude-flow/plugin-financial-risk` | 0.1.0 | Financial risk assessment and modeling |\n| `@claude-flow/plugin-legal-contracts` | 0.1.0 | Legal contract analysis and generation |\n\n### Plugin Development\n\n```bash\n# Create a new plugin from template\nnpx claude-flow@v3alpha plugins create my-plugin\n\n# Test locally\nnpx claude-flow@v3alpha plugins install ./path/to/my-plugin\n\n# Publish to registry (requires Pinata credentials)\nnpx claude-flow@v3alpha plugins publish\n```\n\nRegistry source: IPFS via Pinata (`QmXbfEAaR7D2Ujm4GAkbwcGZQMHqAMpwDoje4583uNP834`)\n\n## Support\n\n- Documentation: https://github.com/ruvnet/claude-flow\n- Issues: https://github.com/ruvnet/claude-flow/issues\n\n---\n\nRemember: **Claude Flow coordinates, Claude Code creates!**\n\n## Gateway-Delegated Development (meta-llm dev-bridge)\n\nFor complex reasoning, architecture decisions, or hard bug-fixes, **delegate via the\n`metallm_delegate` MCP tool rather than solving inline.** The meta-llm gateway governs the\nwork: it routes cheap-tier-first, escalates genuinely-hard tasks to the frontier (Fable),\nand meters every call — so delegation is cost-governed and preserves the main session's context.\n\n- **Default to `cognitum-auto`** — the gateway picks the tier by difficulty. Only pass an\n  explicit tier (`cognitum-low|mid|high`) when you must force one.\n- Prompt-wrapping does **not** inflate cost — the gateway normalizes host scaffolds so an\n  everyday sub-task still routes to the cheap tier. Trust `cognitum-auto`.\n- Use **`metallm_delegate`** for agentic sub-tasks needing tools/files in a working dir\n  (its `cwd` is sandboxed); use **`metallm_ask`** for a single-shot question — it returns\n  the gateway's real metered cost + resolved tier/model in-band.\n- Reserve the main (inline) session for orchestration, integration, and final review;\n  push expensive per-sub-task reasoning through the gateway.\n\n**Setup (per developer, local — never committed):** register the `metallm-dev-bridge` MCP\nserver via a local `.mcp.json` (gitignored) and export your gateway key as `COGNITUM_DEV_KEY`\nin your shell. Build steps + the exact `.mcp.json` block are in the internal meta-llm\ndev-bridge README. **Never commit the key or an inline gateway URL.**\n\n### `ask` vs `delegate` — pick by task shape (load-bearing)\n\n**Use `metallm_ask` for single-shot facts, summaries, classification, and small code\nquestions. Use `metallm_delegate` only when the task needs autonomous multi-step execution\nor isolated agent context.**\n\nWhy the split is strict: `metallm_delegate` spawns a full `claude -p` sub-agent, which loads\nits entire harness context **even for a trivial task** — measured floor ≈ **$0.26/call**\n(~43k input tokens) before any real work. `metallm_ask` is a single gateway completion —\nmeasured ≈ **$0.0001** for a small query, ~2500× cheaper. So delegating casually is\nexpensive at volume; `delegate` pays off only when offloading the sub-task's context from\nthe main session is worth the floor. When in doubt, `ask`.\n\nRouting caveat (tracked): `metallm_ask` **auto** currently over-tiers some trivial prompts to\n`mid` (sonnet-5) instead of `low` — the bridge's `/v1/messages` path may miss ADR-236\nhost-normalization (meta-llm issue #38). Forced tiers work correctly; cost impact is small\nper call but real at volume.\n","AGENTS.md":"# Claude Flow V3 - Agent Guide\n\n> **For OpenAI Codex CLI** - Agentic AI Foundation standard\n> Skills: `$skill-name` | Config: `.agents/config.toml`\n\n---\n\n## 📢 TL;DR - READ THIS FIRST\n\n```\n╔═══════════════════════════════════════════════════════════════════════════╗\n║  1. claude-flow = LEDGER (tracks state, stores memory, coordinates)       ║\n║  2. Codex = EXECUTOR (writes code, runs commands, creates files)          ║\n║  3. NEVER stop after calling claude-flow - IMMEDIATELY continue working   ║\n║  4. If you need something BUILT/EXECUTED, YOU do it, not claude-flow      ║\n║  5. ALWAYS search memory BEFORE starting: memory search --query \"task\"    ║\n║  6. ALWAYS store patterns AFTER success: memory store --namespace patterns║\n╚═══════════════════════════════════════════════════════════════════════════╝\n```\n\n**Workflow (Use MCP Tools):**\n1. `memory_search(query=\"task keywords\")` → LEARN from past patterns (score > 0.7 = use it)\n2. `swarm_init(topology=\"hierarchical\")` → coordination record (instant)\n3. **YOU write the code / run the commands** ← THIS IS WHERE WORK HAPPENS\n4. `memory_store(key=\"pattern-x\", value=\"what worked\", namespace=\"patterns\")` → REMEMBER for next time\n\n---\n\n## Ruflo Policy-Governed Concurrent Codex Workflow\n\nRuflo is the coordination ledger and policy decision point. Codex agents are\nthe executors. Coordination records do not write code or run tests.\n\nUse `guidance_brain({ mode: \"recommend\", task: \"...\" })` to select Ruflo\ncapabilities from the live MCP registry. A registered tool is not necessarily\nconfigured, reachable, healthy, or authorized. If it is unavailable, continue\nwith compatible guidance tools, CLI discovery, and repository instructions.\n\n1. Recall relevant AgentDB memory and ADRs.\n2. Inspect source, runtime, dependencies, policy, and health.\n3. Route to the smallest capable topology, agents, skills, and tools.\n4. Plan acceptance criteria, safety envelope, ownership, and validation.\n5. Execute with Codex workers in isolated scopes; Ruflo records coordination.\n6. Test focused, regression, and failure paths.\n7. Validate types, security, policy, compatibility, and artifact integrity.\n8. Benchmark a source-bound candidate against a source-bound baseline.\n9. Optimize only measured bottlenecks without weakening safety.\n10. Bind claims and evidence into exact source/build receipts.\n11. Reconcile handoffs and disclose unresolved limitations.\n12. Publish only through a separately authorized release gate.\n\nHard invariants:\n\n- Never run two writers in one worktree.\n- Delegation may only reduce tools, servers, namespaces, network, spend,\n  concurrency, expiry, and depth.\n- Policy denial cancels dependent work before side effects.\n- MetaHarness may evaluate candidates concurrently, but only ADR-322A may\n  promote them and MetaHarness may never expand its own SafetyEnvelope.\n- Do not commit, push, merge, release, or remove worktrees unless authorized.\n- Existing installations migrate in `legacy` policy mode; use `observe` before\n  switching to `enforce`.\n\nRepository harness integration:\n\n- If tracked repository instructions define a collaboration harness, start its\n  session only after assigning an isolated worktree.\n- Inspect existing claims, acquire exact paths/resources/ports, renew leases,\n  check acknowledged inbox messages at integration boundaries, and release ownership on\n  handoff or exit.\n- A repository lease coordinates ownership; it does not grant authorization.\n  Protected work still requires the ADR-324/325 action capability and current\n  fencing epoch.\n- In-memory reference adapters demonstrate semantics; they are not distributed,\n  restart-durable release authorities.\n- Heartbeats and lease expiry establish liveness; a PID is diagnostic only.\n- `HEAD` alone is not an exact source-state identity in a dirty worktree.\n  Release evidence must bind a clean commit or an immutable snapshot of tracked\n  and untracked changes.\n\nUseful checks:\n\n```bash\nnpx ruflo policy status\nnpx ruflo policy verify\nnpx ruflo metaharness flywheel status\n```\n\nRepository release contract:\n\n- The stable public train is exactly `@claude-flow/cli`, `claude-flow`, and\n  `ruflo`; internal `@claude-flow/*` components are bundled and are not part of\n  a normal standalone publish.\n- Publish from a clean, reviewed source state in that order.\n- Only the CLI publish receives the helper-signing configuration from\n  `ruv-dev`; use the existing authenticated npm session for publication.\n- Run `node scripts/audit-umbrella-version-lockstep.mjs`, verify all three\n  registry versions, and align `latest`, `alpha`, and `v3alpha`.\n\n---\n\n## 🚨 CRITICAL: CODEX DOES THE WORK, CLAUDE-FLOW ORCHESTRATES\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│  CLAUDE-FLOW = ORCHESTRATOR (tracks state, coordinates)     │\n│  CODEX = WORKER (writes code, runs commands, implements)    │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### ❌ WRONG: Expecting claude-flow to execute tasks\n```bash\nnpx claude-flow swarm start --objective \"Build API\"\n# WRONG: Waiting for claude-flow to build the API\n# Claude-flow does NOT execute code!\n```\n\n### ✅ CORRECT: Codex executes, claude-flow tracks\n```bash\n# 1. Tell claude-flow what you're doing (optional coordination)\nnpx claude-flow swarm init --topology hierarchical --max-agents 1\nnpx claude-flow agent spawn --type coder --name codex-worker\n\n# 2. YOU (CODEX) DO THE ACTUAL WORK:\nmkdir -p src\ncat > src/api.ts << 'EOF'\nexport function hello() { return \"Hello World\"; }\nEOF\n\n# 3. Report to claude-flow what you did (optional)\nnpx claude-flow memory store --key \"api-created\" --value \"src/api.ts\" --namespace results\n```\n\n### The Division of Labor\n\n| Component | Role | Examples |\n|-----------|------|----------|\n| **CODEX** | EXECUTES | Write files, run tests, create code, shell commands |\n| **claude-flow** | ORCHESTRATES | Track agents, store memory, coordinate tasks |\n\n---\n\n## ⛔ DON'T STOP AFTER CALLING CLAUDE-FLOW\n\n```\n┌─────────────────────────────────────────────────────────────────────────┐\n│  ❌ WRONG: Call claude-flow → STOP → Wait for results                   │\n│  ✅ RIGHT: Call claude-flow → IMMEDIATELY continue → YOU do the work    │\n└─────────────────────────────────────────────────────────────────────────┘\n```\n\n### ❌ WRONG Pattern (Stopping)\n```bash\nnpx claude-flow swarm init --topology hierarchical\nnpx claude-flow agent spawn --type coder --name worker-1\nnpx claude-flow swarm start --objective \"Build hello world\"\n# WRONG: Codex stops here and waits for something to happen\n# Nothing will happen! Claude-flow doesn't execute code!\n```\n\n### ✅ CORRECT Pattern (Continue Immediately)\n```bash\n# Step 1: Coordination (optional)\nnpx claude-flow swarm init --topology hierarchical\nnpx claude-flow agent spawn --type coder --name worker-1\n\n# Step 2: IMMEDIATELY DO THE WORK YOURSELF - DON'T WAIT!\necho 'console.log(\"Hello World!\");' > hello.js\nnode hello.js\n\n# Step 3: Report what you did\nnpx claude-flow memory store --key \"result\" --value \"Hello World printed\" --namespace results\n```\n\n### The Rule\n**After ANY claude-flow command, IMMEDIATELY continue with your own work.**\n\nClaude-flow commands return instantly. They create coordination RECORDS only.\nYou must ALWAYS follow up with YOUR OWN execution.\n\n| After This... | IMMEDIATELY Do This... |\n|---------------|----------------------|\n| `swarm init` | Start writing code |\n| `agent spawn` | Continue implementation |\n| `task create` | Execute the task yourself |\n| `swarm start` | Begin actual work |\n\n---\n\n### When to Use Claude-Flow Commands\n\n| Use Case | Claude-Flow Command | Then Codex Does |\n|----------|---------------------|-----------------|\n| Track progress | `memory store --key \"step1\" --value \"done\"` | Continue to next step |\n| Multi-step tasks | `task create --description \"step 2\"` | Execute step 2 |\n| Store results | `memory store --key \"output\" --value \"...\"` | Move on |\n| Coordinate | `swarm init` | Start working |\n\n### Hello World - Correct Pattern\n\n```bash\n# STEP 1: Optional - register with orchestrator\nnpx claude-flow swarm init --topology mesh --max-agents 1\n\n# STEP 2: CODEX DOES THE WORK\necho 'console.log(\"Hello World!\");' > hello.js\nnode hello.js\n\n# STEP 3: Optional - report completion\nnpx claude-flow memory store --key \"hello-result\" --value \"printed Hello World\" --namespace results\n```\n\n**REMEMBER: If you need something DONE, YOU do it. Claude-flow just tracks.**\n\n---\n\n## ⚡ QUICK COMMANDS (NO DISCOVERY NEEDED)\n\n### Spawn N-Agent Swarm (Copy-Paste Ready)\n\n```bash\n# 5-AGENT SWARM - Run these commands in sequence:\nnpx claude-flow swarm init --topology hierarchical --max-agents 8\nnpx claude-flow agent spawn --type coordinator --name coord-1\nnpx claude-flow agent spawn --type coder --name coder-1\nnpx claude-flow agent spawn --type coder --name coder-2\nnpx claude-flow agent spawn --type tester --name tester-1\nnpx claude-flow agent spawn --type reviewer --name reviewer-1\nnpx claude-flow swarm start --objective \"Your task here\" --strategy development\n```\n\n### Common Swarm Patterns\n\n| Task | Exact Command |\n|------|---------------|\n| Init hierarchical swarm | `npx claude-flow swarm init --topology hierarchical --max-agents 8` |\n| Init mesh swarm | `npx claude-flow swarm init --topology mesh --max-agents 5` |\n| Init V3 mode (15 agents) | `npx claude-flow swarm init --v3-mode` |\n| Spawn coder | `npx claude-flow agent spawn --type coder --name coder-1` |\n| Spawn tester | `npx claude-flow agent spawn --type tester --name tester-1` |\n| Spawn coordinator | `npx claude-flow agent spawn --type coordinator --name coord-1` |\n| Spawn architect | `npx claude-flow agent spawn --type architect --name arch-1` |\n| Spawn reviewer | `npx claude-flow agent spawn --type reviewer --name rev-1` |\n| Spawn researcher | `npx claude-flow agent spawn --type researcher --name res-1` |\n| Start swarm | `npx claude-flow swarm start --objective \"task\" --strategy development` |\n| Check swarm status | `npx claude-flow swarm status` |\n| List agents | `npx claude-flow agent list` |\n| Stop swarm | `npx claude-flow swarm stop` |\n\n### Agent Types (Use with `--type`)\n\n| Type | Purpose |\n|------|---------|\n| `coordinator` | Orchestrates other agents |\n| `coder` | Writes code |\n| `tester` | Writes tests |\n| `reviewer` | Reviews code |\n| `architect` | Designs systems |\n| `researcher` | Analyzes requirements |\n| `security-architect` | Security design |\n| `performance-engineer` | Optimization |\n\n### Task Commands\n\n| Action | Command |\n|--------|---------|\n| Create task | `npx claude-flow task create --type implementation --description \"desc\"` |\n| List tasks | `npx claude-flow task list` |\n| Assign task | `npx claude-flow task assign TASK_ID --agent AGENT_NAME` |\n| Task status | `npx claude-flow task status TASK_ID` |\n| Cancel task | `npx claude-flow task cancel TASK_ID` |\n\n### Memory Commands\n\n| Action | Command |\n|--------|---------|\n| Store | `npx claude-flow memory store --key \"key\" --value \"value\" --namespace patterns` |\n| Search | `npx claude-flow memory search --query \"search terms\"` |\n| List | `npx claude-flow memory list --namespace patterns` |\n| Retrieve | `npx claude-flow memory retrieve --key \"key\"` |\n\n---\n\n## 🚀 SWARM RECIPES\n\n### Recipe 1: Hello World Test (COMPLETE EXAMPLE)\n\n**Step 1: Setup coordination** (returns instantly - don't stop!)\n```bash\nnpx claude-flow swarm init --topology mesh --max-agents 5\nnpx claude-flow agent spawn --type coder --name hello-main\n# ⚠️ DON'T STOP HERE - CONTINUE IMMEDIATELY TO STEP 2\n```\n\n**Step 2: YOU (Codex) execute the task** (THIS IS THE REAL WORK)\n```bash\n# ✅ YOU create the file\necho 'console.log(\"Hello World from Swarm!\");' > /tmp/hello-swarm.js\n\n# ✅ YOU execute it\nnode /tmp/hello-swarm.js\n# Output: Hello World from Swarm!\n```\n\n**Step 3: Report completion** (optional - store results)\n```bash\nnpx claude-flow memory store --key \"hello-world-result\" --value \"Executed: Hello World from Swarm!\" --namespace results\n```\n\n### Recipe 1b: 5-Agent Concurrent Hello World (COMPLETE)\n```bash\n# COORDINATION (instant - creates records only)\nnpx claude-flow swarm init --topology hierarchical --max-agents 5\nfor i in 1 2 3 4 5; do\n  npx claude-flow agent spawn --type coder --name \"worker-$i\"\ndone\n\n# ⚠️ NOW YOU DO THE ACTUAL CONCURRENT WORK:\nfor i in 1 2 3 4 5; do\n  (echo \"Worker $i: Hello World!\" && sleep 0.$i) &\ndone\nwait\necho \"All 5 workers completed!\"\n\n# REPORT (optional)\nnpx claude-flow memory store --key \"concurrent-result\" --value \"5 workers completed\" --namespace results\n```\n\n### Recipe 1b: Hello World (Single Command Block)\n```bash\n# All-in-one execution\nnpx claude-flow swarm init --topology mesh --max-agents 5 && \\\nnpx claude-flow agent spawn --type coder --name hello-main && \\\nnpx claude-flow swarm start --objective \"Print hello world\" --strategy development && \\\necho 'console.log(\"Hello World from Swarm!\");' > /tmp/hello-swarm.js && \\\nnode /tmp/hello-swarm.js && \\\nnpx claude-flow memory store --key \"hello-world-result\" --value \"Success\" --namespace results\n```\n\n### Recipe 2: Feature Implementation (6 Agents)\n```bash\nnpx claude-flow swarm init --topology hierarchical --max-agents 8\nnpx claude-flow agent spawn --type coordinator --name lead\nnpx claude-flow agent spawn --type architect --name arch\nnpx claude-flow agent spawn --type coder --name impl-1\nnpx claude-flow agent spawn --type coder --name impl-2\nnpx claude-flow agent spawn --type tester --name test\nnpx claude-flow agent spawn --type reviewer --name review\nnpx claude-flow swarm start --objective \"Implement [feature]\" --strategy development\n```\n\n### Recipe 3: Bug Fix (4 Agents)\n```bash\nnpx claude-flow swarm init --topology hierarchical --max-agents 4\nnpx claude-flow agent spawn --type coordinator --name lead\nnpx claude-flow agent spawn --type researcher --name debug\nnpx claude-flow agent spawn --type coder --name fix\nnpx claude-flow agent spawn --type tester --name verify\nnpx claude-flow swarm start --objective \"Fix [bug]\" --strategy development\n```\n\n### Recipe 4: Security Audit (3 Agents)\n```bash\nnpx claude-flow swarm init --topology hierarchical --max-agents 4\nnpx claude-flow agent spawn --type coordinator --name lead\nnpx claude-flow agent spawn --type security-architect --name audit\nnpx claude-flow agent spawn --type reviewer --name review\nnpx claude-flow swarm start --objective \"Security audit\" --strategy development\n```\n\n### Recipe 5: V3 Full Coordination (15 Agents)\n```bash\nnpx claude-flow swarm init --v3-mode\nnpx claude-flow swarm coordinate --agents 15\n```\n\n---\n\n## 📋 BEHAVIORAL RULES\n\n- **YOU (CODEX) execute tasks** - claude-flow only orchestrates\n- Do what is asked; nothing more, nothing less\n- NEVER create files unless absolutely necessary\n- ALWAYS prefer editing existing files\n- NEVER save to root folder\n- NEVER commit secrets or .env files\n- ALWAYS read a file before editing it\n- NEVER wait for claude-flow to \"do work\" - it doesn't execute, YOU do\n- Use claude-flow commands to TRACK progress, not to EXECUTE tasks\n\n## 📁 FILE ORGANIZATION\n\n| Directory | Purpose |\n|-----------|---------|\n| `/src` | Source code |\n| `/tests` | Test files |\n| `/docs` | Documentation |\n| `/config` | Configuration |\n| `/scripts` | Utility scripts |\n\n## 🎯 WHEN TO USE SWARMS\n\n**USE SWARM:**\n- Multiple files (3+)\n- New feature implementation\n- Cross-module refactoring\n- API changes with tests\n- Security-related changes\n- Performance optimization\n\n**SKIP SWARM:**\n- Single file edits\n- Simple bug fixes (1-2 lines)\n- Documentation updates\n- Configuration changes\n\n---\n\n## 🔧 CLI REFERENCE\n\n### Swarm Commands\n```bash\nnpx claude-flow swarm init [--topology TYPE] [--max-agents N] [--v3-mode]\nnpx claude-flow swarm start --objective \"task\" --strategy [development|research]\nnpx claude-flow swarm status [SWARM_ID]\nnpx claude-flow swarm stop [SWARM_ID]\nnpx claude-flow swarm scale --count N\nnpx claude-flow swarm coordinate --agents N\n```\n\n### Agent Commands\n```bash\nnpx claude-flow agent spawn --type TYPE --name NAME\nnpx claude-flow agent list [--filter active|idle|busy]\nnpx claude-flow agent status AGENT_ID\nnpx claude-flow agent stop AGENT_ID\nnpx claude-flow agent metrics [AGENT_ID]\nnpx claude-flow agent health\nnpx claude-flow agent logs AGENT_ID\n```\n\n### Task Commands\n```bash\nnpx claude-flow task create --type TYPE --description \"desc\"\nnpx claude-flow task list [--all]\nnpx claude-flow task status TASK_ID\nnpx claude-flow task assign TASK_ID --agent AGENT_NAME\nnpx claude-flow task cancel TASK_ID\nnpx claude-flow task retry TASK_ID\n```\n\n### Memory Commands\n```bash\nnpx claude-flow memory store --key KEY --value VALUE [--namespace NS]\nnpx claude-flow memory search --query \"terms\" [--namespace NS]\nnpx claude-flow memory list [--namespace NS]\nnpx claude-flow memory retrieve --key KEY [--namespace NS]\nnpx claude-flow memory init [--force]\n```\n\n### Hooks Commands\n```bash\nnpx claude-flow hooks pre-task --description \"task\"\nnpx claude-flow hooks post-task --task-id ID --success true\nnpx claude-flow hooks route --task \"task\"\nnpx claude-flow hooks session-start --session-id ID\nnpx claude-flow hooks session-end --export-metrics true\nnpx claude-flow hooks worker list\nnpx claude-flow hooks worker dispatch --trigger audit\n```\n\n### System Commands\n```bash\nnpx claude-flow init [--wizard] [--codex] [--full]\nnpx claude-flow daemon start\nnpx claude-flow daemon stop\nnpx claude-flow daemon status\nnpx claude-flow doctor [--fix]\nnpx claude-flow status\nnpx claude-flow mcp start\n```\n\n---\n\n## 🔌 TOPOLOGIES\n\n| Topology | Use Case | Command Flag |\n|----------|----------|--------------|\n| `hierarchical` | Coordinated teams, anti-drift | `--topology hierarchical` |\n| `mesh` | Peer-to-peer, equal agents | `--topology mesh` |\n| `hierarchical-mesh` | Hybrid (recommended for V3) | `--topology hierarchical-mesh` |\n| `ring` | Sequential processing | `--topology ring` |\n| `star` | Central coordinator | `--topology star` |\n| `adaptive` | Dynamic switching | `--topology adaptive` |\n\n## 🤖 AGENT TYPES\n\n### Core\n`coordinator`, `coder`, `tester`, `reviewer`, `architect`, `researcher`\n\n### Specialized\n`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`\n\n### Swarm Coordination\n`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`\n\n### Consensus\n`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`\n\n---\n\n## ⚙️ CONFIGURATION\n\n### Default Swarm Config\n- Topology: `hierarchical`\n- Max Agents: 8\n- Strategy: `specialized`\n- Consensus: `raft`\n- Memory: `hybrid`\n\n### Environment Variables\n```bash\nCLAUDE_FLOW_CONFIG=./claude-flow.config.json\nCLAUDE_FLOW_LOG_LEVEL=info\nCLAUDE_FLOW_MEMORY_BACKEND=hybrid\n```\n\n---\n\n## 🔗 SKILLS\n\nInvoke with `$skill-name`:\n\n| Skill | Purpose |\n|-------|---------|\n| `$swarm-orchestration` | Multi-agent coordination |\n| `$memory-management` | Pattern storage/retrieval |\n| `$sparc-methodology` | Structured development |\n| `$security-audit` | Security scanning |\n| `$performance-analysis` | Profiling |\n| `$github-automation` | CI/CD management |\n| `$hive-mind` | Byzantine consensus |\n| `$neural-training` | Pattern learning |\n\n---\n\n---\n\n## 🔌 MCP INTEGRATION (Learning & Coordination)\n\nCodex doesn't have native hooks like Claude Code, but uses **MCP (Model Context Protocol)** for learning and coordination.\n\n### MCP Auto-Registration\n\nWhen you run `npx claude-flow init --codex`, the MCP server is **automatically registered** with Codex.\n\n```bash\n# Verify MCP is registered:\ncodex mcp list\n\n# Expected output:\n# Name         Command  Args                   Status\n# claude-flow  npx      claude-flow mcp start  enabled\n\n# If not present, add manually:\ncodex mcp add claude-flow -- npx claude-flow mcp start\n```\n\n### Test MCP Connection\n```bash\n# Test MCP server starts correctly:\nnpx claude-flow mcp start --test\n```\n\n### MCP Tools Available\nOnce added, Codex can use these tools via MCP:\n\n**Coordination:**\n| Tool | Purpose |\n|------|---------|\n| `swarm_init` | Initialize swarm (topology, maxAgents) |\n| `swarm_status` | Check swarm state |\n| `agent_spawn` | Register agent roles |\n| `agent_status` | Check agent state |\n| `task_orchestrate` | Coordinate multi-agent tasks |\n\n**Learning & Memory (USE THESE!):**\n| Tool | Purpose | When |\n|------|---------|------|\n| `memory_search` | Semantic vector search | BEFORE every task |\n| `memory_store` | Store patterns with embeddings | AFTER success |\n| `memory_retrieve` | Get by exact key | When key is known |\n| `neural_train` | Train on patterns | Periodic improvement |\n| `neural_status` | Check learning state | Debugging |\n\n**Hive Mind (Advanced):**\n| Tool | Purpose |\n|------|---------|\n| `hive-mind_init` | Byzantine consensus swarm |\n| `hive-mind_spawn` | Spawn hive workers |\n| `hive-mind_broadcast` | Message all workers |\n\n### Self-Learning via MCP Tools (PREFERRED)\n\nUse MCP tools directly - faster than CLI commands:\n\n**BEFORE starting any task - SEARCH for patterns:**\n```\nUse tool: memory_search\n  query: \"keywords related to your task\"\n  namespace: \"patterns\"\n```\n\n**AFTER completing successfully - STORE the pattern:**\n```\nUse tool: memory_store\n  key: \"pattern-[descriptive-name]\"\n  value: \"What worked: approach, code patterns, gotchas\"\n  namespace: \"patterns\"\n```\n\n### MCP Learning Workflow (Use This!)\n\n```\n1. LEARN: memory_search(query=\"task keywords\", namespace=\"patterns\")\n   → If score > 0.7, USE that pattern\n\n2. COORDINATE: swarm_init(topology=\"hierarchical\")\n   → agent_spawn(type=\"coder\", name=\"worker-1\")\n\n3. EXECUTE: YOU write the code, run commands, create files\n\n4. REMEMBER: memory_store(key=\"pattern-x\", value=\"what worked\", namespace=\"patterns\")\n```\n\n### MCP Tools for Learning\n\n| Tool | Purpose | When to Use |\n|------|---------|-------------|\n| `memory_search` | Find similar past patterns | BEFORE starting any task |\n| `memory_store` | Save successful patterns | AFTER completing a task |\n| `memory_retrieve` | Get specific pattern by key | When you know the exact key |\n| `neural_train` | Train on successful patterns | After multiple successes |\n\n### Example: Learning-Enabled Task\n\n```\nSTEP 1 - LEARN:\nUse tool: memory_search\n  query: \"validation utility function\"\n  namespace: \"patterns\"\n\n→ Found: pattern-email-validator (score: 0.82)\n→ Use this pattern as reference!\n\nSTEP 2 - COORDINATE:\nUse tool: swarm_init with topology=\"hierarchical\", maxAgents=3\n\nSTEP 3 - EXECUTE:\nYOU create the files:\n  echo 'export function validate(x) { ... }' > /tmp/validator.js\n  node --test /tmp/validator.js\n\nSTEP 4 - REMEMBER:\nUse tool: memory_store\n  key: \"pattern-phone-validator\"\n  value: \"Phone validation: regex /^\\+?[\\d\\s-]{10,}$/, normalize first, test edge cases\"\n  namespace: \"patterns\"\n```\n\n### Vector Search Tips\n- Searches are SEMANTIC (meaning-based, not just keywords)\n- Score > 0.7 = strong match, use that pattern\n- Score 0.5-0.7 = partial match, adapt as needed\n- Store DETAILED values for better future retrieval\n\n### CLI Fallback (if MCP unavailable)\n```bash\nnpx claude-flow memory search --query \"keywords\" --namespace patterns\nnpx claude-flow memory store --key \"pattern-x\" --value \"what worked\" --namespace patterns\n```\n\n### Coordination via MCP\n\nWhen claude-flow is added as MCP server, Codex can call tools directly:\n```\nUse tool: swarm_init with topology=\"hierarchical\"\nUse tool: memory_store with key=\"result\" value=\"success\"\n```\n\n### config.toml MCP Setup\n```toml\n# ~/.codex/config.toml\n[mcp_servers.claude-flow]\ncommand = \"npx\"\nargs = [\"claude-flow\", \"mcp\", \"start\"]\nenabled = true\n```\n\n---\n\n## 📚 SUPPORT\n\n- Docs: https://github.com/ruvnet/claude-flow\n- Issues: https://github.com/ruvnet/claude-flow/issues\n\n**Remember: Codex executes, claude-flow orchestrates!**\n"},"items":[{"name":"CLAUDE.md","path":"CLAUDE.md","title":"CLAUDE.md","content":"# Claude Code Configuration - Ruflo V3\n\n> Public release train: `@claude-flow/cli`, `claude-flow`, and `ruflo`.\n> Use package manifests and the registry as version truth; do not copy stale\n> version or capability counts into agent guidance.\n\n## Behavioral Rules (Always Enforced)\n\n- Do what has been asked; nothing more, nothing less\n- NEVER create files unless they're absolutely necessary for achieving your goal\n- ALWAYS prefer editing an existing file to creating a new one\n- NEVER proactively create documentation files (*.md) or README files unless explicitly requested\n- NEVER save working files, text/mds, or tests to the root folder\n- Never continuously check status after spawning a swarm — wait for results\n- ALWAYS read a file before editing it\n- NEVER commit secrets, credentials, or .env files\n\n## Capability Brain and Governed Implementation\n\nRuflo is the coordination ledger and policy decision point. Claude Code\nexecutes code, tests, commands, and file changes. A Ruflo coordination call\nrecords work; it does not perform the implementation.\n\nWhen registered, call\n`guidance_brain({ mode: \"recommend\", task: \"...\" })` before complex Ruflo\nwork. Use its live registry rather than guessing tool names. Treat\n`registered`, `configured`, `reachable`, `healthy`, and `authorized` as\nseparate facts. If unavailable, continue with compatible guidance tools, CLI\ndiscovery, and these repository instructions.\n\nUse this loop: recall → inspect → route → plan → execute → test → validate →\nbenchmark → optimize → receipt → handoff → separately authorized publish.\n\n## File Organization\n\n- NEVER save to root folder — use the directories below\n- Use `/src` for source code files\n- Use `/tests` for test files\n- Use `/docs` for documentation and markdown files\n- Use `/config` for configuration files\n- Use `/scripts` for utility scripts\n- Use `/examples` for example code\n\n## Project Architecture\n\n- Follow Domain-Driven Design with bounded contexts\n- Keep files under 500 lines\n- Use typed interfaces for all public APIs\n- Prefer TDD London School (mock-first) for new code\n- Use event sourcing for state changes\n- Ensure input validation at system boundaries\n\n### Key Packages\n\n| Package | Path | Purpose |\n|---------|------|---------|\n| `@claude-flow/cli` | `v3/@claude-flow/cli/` | CLI entry point (26 commands) |\n| `@claude-flow/codex` | `v3/@claude-flow/codex/` | Dual-mode Claude + Codex collaboration |\n| `@claude-flow/guidance` | `v3/@claude-flow/guidance/` | Governance control plane |\n| `@claude-flow/hooks` | `v3/@claude-flow/hooks/` | 17 hooks + 12 workers |\n| `@claude-flow/memory` | `v3/@claude-flow/memory/` | AgentDB + HNSW search |\n| `@claude-flow/security` | `v3/@claude-flow/security/` | Input validation, CVE remediation |\n\n## Concurrent Automated Development\n\n- Parallelize independent research, tests, reviews, and non-overlapping\n  implementation.\n- Never allow two writers in one worktree. Give every writing agent an isolated\n  worktree and explicit file ownership.\n- Read-only agents may share a checkout; writing agents may not.\n- Only the integration owner edits shared manifests and lockfiles or reconciles\n  overlapping changes.\n- Continue independent local work after spawning agents; wait only when a real\n  dependency blocks progress. Do not repeatedly poll.\n- A lease or work claim coordinates ownership; it never grants authority.\n- Bind tests, benchmarks, policy decisions, and handoffs to an exact clean\n  commit or immutable dirty-worktree snapshot.\n- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose and\n  evaluate candidates, but cannot self-promote or expand tools, network,\n  secrets, spend, concurrency, or release authority.\n\n---\n\n## Swarm Orchestration\n\n- MUST initialize the swarm using MCP tools when starting complex tasks\n- MUST spawn concurrent agents using Claude Code's Task tool\n- Never use MCP tools alone for execution — Task tool agents do the actual work\n\n### MCP + Task Tool in SAME Message\n\n- MUST call MCP tools AND Task tool in ONE message for complex work\n- Always call MCP first, then IMMEDIATELY call Task tool to spawn agents\n\n### 3-Tier Model Routing (ADR-026, ADR-143)\n\n| Tier | Handler | Latency | Cost | Use Cases |\n|------|---------|---------|------|-----------|\n| **1** | Deterministic codemod | ~1ms | $0 | Structural transforms with **no LLM**: `var-to-const`, `remove-console`, `add-logging` |\n| **2** | Haiku | ~500ms | $0.0002 | Simple tasks, low complexity (<30%) |\n| **3** | Sonnet/Opus | 2-5s | $0.003-0.015 | Complex reasoning, architecture, security (>30%) |\n\n- Always check for `[CODEMOD_AVAILABLE]` or `[TASK_MODEL_RECOMMENDATION]` before spawning agents\n- 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`\n- `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)\n- 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 path\n\n## Swarm Configuration & Anti-Drift\n\n### Anti-Drift Coding Swarm (PREFERRED DEFAULT)\n\n- ALWAYS use hierarchical topology for coding swarms\n- Keep maxAgents at 6-8 for tight coordination\n- Use specialized strategy for clear role boundaries\n- Use `raft` consensus for hive-mind (leader maintains authoritative state)\n- Run frequent checkpoints via `post-task` hooks\n- Keep shared memory namespace for all agents\n- Keep task cycles short with verification gates\n\n```javascript\nmcp__ruv-swarm__swarm_init({\n  topology: \"hierarchical\",\n  maxAgents: 8,\n  strategy: \"specialized\"\n})\n```\n\n## Dual-Mode Collaboration (Claude Code + Codex)\n\nThis 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.\n\n### Why Dual-Mode?\n\n| Single Platform | Dual-Mode Collaboration |\n|----------------|------------------------|\n| One model's perspective | Two AI platforms cross-validating |\n| Limited reasoning styles | Complementary strengths |\n| No external verification | Built-in code review |\n| Sequential workflows | Parallel execution |\n\n### Dual-Mode Swarm Protocol\n\nFor complex tasks, spawn both Claude and Codex workers in parallel:\n\n```javascript\n// STEP 1: Initialize dual-mode swarm\nmcp__ruv-swarm__swarm_init({\n  topology: \"hierarchical\",\n  maxAgents: 8,\n  strategy: \"specialized\"\n})\n\n// STEP 2: Spawn BOTH platforms in parallel via Task tool\n// 🔵 Claude Code workers (architecture, security, testing)\nTask(\"Architect\", \"Design the implementation. Store design in memory namespace 'collaboration'.\", \"system-architect\")\nTask(\"Tester\", \"Write tests based on architect's design. Read from 'collaboration' namespace.\", \"tester\")\nTask(\"Reviewer\", \"Review code quality and security. Store findings in 'collaboration'.\", \"reviewer\")\n\n// 🟢 Codex workers (implementation, optimization)\n// Spawn via CLI for Codex platform\nBash(\"npx claude-flow-codex dual run --worker 'codex:coder:Implement the solution based on architect design' --namespace collaboration\")\nBash(\"npx claude-flow-codex dual run --worker 'codex:optimizer:Optimize performance based on implementation' --namespace collaboration\")\n\n// STEP 3: Coordinate via shared memory\nBash(\"npx claude-flow@v3alpha memory store --namespace collaboration --key 'task-context' --value '[task description]'\")\n```\n\n### Collaboration Templates (Pre-Built Pipelines)\n\n| Template | Workers | Pipeline |\n|----------|---------|----------|\n| `feature` | 🔵 Architect → 🟢 Coder → 🔵 Tester → 🟢 Reviewer | Full feature development |\n| `security` | 🔵 Analyst → 🟢 Scanner → 🔵 Reporter | Security audit workflow |\n| `refactor` | 🔵 Architect → 🟢 Refactorer → 🔵 Tester | Code modernization |\n| `bugfix` | 🔵 Researcher → 🟢 Coder → 🔵 Tester | Bug investigation & fix |\n\n### Dual-Mode CLI Commands\n\n```bash\n# Run a collaboration template\nnpx claude-flow-codex dual run feature --task \"Add user authentication with OAuth\"\nnpx claude-flow-codex dual run security --target \"./src\"\nnpx claude-flow-codex dual run refactor --target \"./src/legacy\"\n\n# Custom multi-platform swarm\nnpx claude-flow-codex dual run \\\n  --worker \"claude:architect:Design the API structure\" \\\n  --worker \"codex:coder:Implement REST endpoints\" \\\n  --worker \"claude:tester:Write integration tests\" \\\n  --worker \"codex:reviewer:Review code quality\" \\\n  --namespace \"api-feature\"\n\n# Check collaboration status\nnpx claude-flow-codex dual status\n\n# List available templates\nnpx claude-flow-codex dual templates\n```\n\n### Shared Memory Coordination\n\nAll workers share state via the `collaboration` namespace:\n\n```bash\n# Store context for cross-platform sharing\nnpx claude-flow@v3alpha memory store --namespace collaboration --key \"design-decisions\" --value \"...\"\n\n# Search for patterns across all workers\nnpx claude-flow@v3alpha memory search --namespace collaboration --query \"authentication patterns\"\n\n# Retrieve specific findings\nnpx claude-flow@v3alpha memory retrieve --namespace collaboration --key \"security-findings\"\n```\n\n### Cross-Platform Learning\n\nBoth platforms learn from each other's outputs:\n\n```bash\n# After successful collaboration, train patterns\nnpx claude-flow@v3alpha hooks post-task --task-id \"dual-[id]\" --success true --train-neural true\n\n# Store successful collaboration patterns\nnpx claude-flow@v3alpha memory store --namespace patterns --key \"dual-mode-[pattern]\" --value \"[what worked]\"\n\n# Transfer learnings to both platforms\nnpx claude-flow@v3alpha hooks transfer store --pattern \"dual-collab-success\"\n```\n\n### Worker Dependency Levels\n\nWorkers execute in dependency order:\n\n```\nLevel 0: [🔵 Architect]           # No dependencies - runs first\nLevel 1: [🟢 Coder, 🔵 Tester]    # Depends on Architect\nLevel 2: [🔵 Reviewer]            # Depends on Coder + Tester\nLevel 3: [🟢 Optimizer]           # Depends on Reviewer approval\n```\n\n### Platform Strengths\n\n| Task Type | Preferred Platform | Reason |\n|-----------|-------------------|--------|\n| Architecture & Design | 🔵 Claude | Strong reasoning, system thinking |\n| Implementation | 🟢 Codex | Fast code generation |\n| Security Review | 🔵 Claude | Careful analysis, threat modeling |\n| Performance Optimization | 🟢 Codex | Code-level optimizations |\n| Testing Strategy | 🔵 Claude | Coverage analysis, edge cases |\n| Refactoring | 🟢 Codex | Bulk code transformations |\n\n### Programmatic API\n\n```typescript\nimport { DualModeOrchestrator, CollaborationTemplates } from '@claude-flow/codex';\n\nconst orchestrator = new DualModeOrchestrator({\n  namespace: 'my-feature',\n  memoryBackend: 'hybrid'\n});\n\n// Use pre-built template\nconst workers = CollaborationTemplates.featureDevelopment('Add OAuth login');\n\n// Run collaboration\nconst results = await orchestrator.runCollaboration(workers, 'Implement OAuth feature');\n\n// Access shared memory\nconst designDocs = await orchestrator.getMemory('design-decisions');\n```\n\n---\n\n## Swarm Protocols & Routing\n\n### Auto-Start Swarm Protocol\n\nWhen the user requests a complex task (multi-file changes, feature implementation, refactoring), **immediately execute this pattern in a SINGLE message:**\n\n```javascript\n// STEP 1: Initialize swarm coordination via MCP\nmcp__ruv-swarm__swarm_init({\n  topology: \"hierarchical\",\n  maxAgents: 8,\n  strategy: \"specialized\"\n})\n\n// STEP 2: Spawn NAMED agents concurrently — all in ONE message\n// Each agent knows WHO to message next in the pipeline\nTask({\n  prompt: \"Research requirements and codebase. SendMessage findings to 'architect' when done.\",\n  subagent_type: \"researcher\", name: \"researcher\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for research from 'researcher'. Design implementation. SendMessage design to 'coder'.\",\n  subagent_type: \"system-architect\", name: \"architect\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for design from 'architect'. Implement the solution. SendMessage code paths to 'tester'.\",\n  subagent_type: \"coder\", name: \"coder\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for implementation from 'coder'. Write tests. SendMessage results to 'reviewer'.\",\n  subagent_type: \"tester\", name: \"tester\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for test results from 'tester'. Review code quality and security. Report findings.\",\n  subagent_type: \"reviewer\", name: \"reviewer\", run_in_background: true\n})\n\n// STEP 3: Kick off the pipeline\nSendMessage({ to: \"researcher\", summary: \"Start research\", message: \"[task description and context]\" })\n\n// STEP 4: Batch todos\nTodoWrite({ todos: [\n  {content: \"Research and analyze requirements\", status: \"in_progress\", activeForm: \"Researching\"},\n  {content: \"Design architecture\", status: \"pending\", activeForm: \"Designing\"},\n  {content: \"Implement solution\", status: \"pending\", activeForm: \"Implementing\"},\n  {content: \"Write tests\", status: \"pending\", activeForm: \"Testing\"},\n  {content: \"Review and finalize\", status: \"pending\", activeForm: \"Reviewing\"}\n]})\n\n// Pipeline flow via SendMessage:\n// researcher ──→ architect ──→ coder ──→ tester ──→ reviewer\n```\n\n### Agent Routing (Anti-Drift)\n\n| Code | Task | Agents |\n|------|------|--------|\n| 1 | Bug Fix | coordinator, researcher, coder, tester |\n| 3 | Feature | coordinator, architect, coder, tester, reviewer |\n| 5 | Refactor | coordinator, architect, coder, reviewer |\n| 7 | Performance | coordinator, perf-engineer, coder |\n| 9 | Security | coordinator, security-architect, auditor |\n| 11 | Memory | coordinator, memory-specialist, perf-engineer |\n| 13 | Docs | researcher, api-docs |\n\n**Codes 1-11: hierarchical/specialized (anti-drift). Code 13: mesh/balanced**\n\n### Task Complexity Detection\n\n**AUTO-INVOKE SWARM when task involves:**\n- Multiple files (3+)\n- New feature implementation\n- Refactoring across modules\n- API changes with tests\n- Security-related changes\n- Performance optimization\n- Database schema changes\n\n**SKIP SWARM for:**\n- Single file edits\n- Simple bug fixes (1-2 lines)\n- Documentation updates\n- Configuration changes\n- Quick questions/exploration\n\n## Project Configuration\n\nThis project is configured with Claude Flow V3 (Anti-Drift Defaults):\n- **Topology**: hierarchical (prevents drift via central coordination)\n- **Max Agents**: 8 (smaller team = less drift)\n- **Strategy**: specialized (clear roles, no overlap)\n- **Consensus**: raft (leader maintains authoritative state)\n- **Memory Backend**: hybrid (SQLite + AgentDB)\n- **HNSW Indexing**: Enabled (measured ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force; ANN wins above the crossover)\n- **Neural Learning**: Enabled (SONA)\n\n## V3 CLI Commands (26 Commands, 140+ Subcommands)\n\n### Core Commands\n\n| Command | Subcommands | Description |\n|---------|-------------|-------------|\n| `init` | 4 | Project initialization with wizard, presets, skills, hooks |\n| `agent` | 8 | Agent lifecycle (spawn, list, status, stop, metrics, pool, health, logs) |\n| `swarm` | 6 | Multi-agent swarm coordination and orchestration |\n| `memory` | 11 | AgentDB memory with HNSW vector search (measured ~1.9x–4.7x vs brute force above crossover) |\n| `mcp` | 9 | MCP server management and tool execution |\n| `task` | 6 | Task creation, assignment, and lifecycle |\n| `session` | 7 | Session state management and persistence |\n| `config` | 7 | Configuration management and provider setup |\n| `status` | 3 | System status monitoring with watch mode |\n| `start` | 3 | Service startup and quick launch |\n| `workflow` | 6 | Workflow execution and template management |\n| `hooks` | 17 | Self-learning hooks + 12 background workers |\n| `hive-mind` | 6 | Queen-led Byzantine fault-tolerant consensus |\n\n### Advanced Commands\n\n| Command | Subcommands | Description |\n|---------|-------------|-------------|\n| `daemon` | 5 | Background worker daemon (start, stop, status, trigger, enable) |\n| `neural` | 5 | Neural pattern training (train, status, patterns, predict, optimize) |\n| `security` | 6 | Security scanning (scan, audit, cve, threats, validate, report) |\n| `performance` | 5 | Performance profiling (benchmark, profile, metrics, optimize, report) |\n| `providers` | 5 | AI providers (list, add, remove, test, configure) |\n| `plugins` | 5 | Plugin management (list, install, uninstall, enable, disable) |\n| `deployment` | 5 | Deployment management (deploy, rollback, status, environments, release) |\n| `embeddings` | 4 | Vector embeddings (embed, batch, search, init) — agentic-flow ONNX backend (speedup unverified, no benchmark) |\n| `claims` | 4 | Claims-based authorization (check, grant, revoke, list) |\n| `migrate` | 5 | V2 to V3 migration with rollback support |\n| `process` | 4 | Background process management |\n| `doctor` | 1 | System diagnostics with health checks |\n| `completions` | 4 | Shell completions (bash, zsh, fish, powershell) |\n\n### Quick CLI Examples\n\n```bash\n# Initialize project\nnpx claude-flow@v3alpha init --wizard\n\n# Start daemon with background workers\nnpx claude-flow@v3alpha daemon start\n\n# Spawn an agent\nnpx claude-flow@v3alpha agent spawn -t coder --name my-coder\n\n# Initialize swarm\nnpx claude-flow@v3alpha swarm init --v3-mode\n\n# Search memory (HNSW-indexed)\nnpx claude-flow@v3alpha memory search -q \"authentication patterns\"\n\n# System diagnostics\nnpx claude-flow@v3alpha doctor --fix\n\n# Security scan\nnpx claude-flow@v3alpha security scan --depth full\n\n# Performance benchmark\nnpx claude-flow@v3alpha performance benchmark --suite all\n```\n\n## Headless Background Instances (claude -p)\n\nUse `claude -p` (print/pipe mode) to spawn headless Claude instances for parallel background work. These run non-interactively and return results to stdout.\n\n### Basic Usage\n\n```bash\n# Single headless task\nclaude -p \"Analyze the authentication module for security issues\"\n\n# With model selection\nclaude -p --model haiku \"Format this config file\"\nclaude -p --model opus \"Design the database schema for user management\"\n\n# With output format\nclaude -p --output-format json \"List all TODO comments in src/\"\nclaude -p --output-format stream-json \"Refactor the error handling in api.ts\"\n\n# With budget limits\nclaude -p --max-budget-usd 0.50 \"Run comprehensive security audit\"\n\n# With specific tools allowed\nclaude -p --allowedTools \"Read,Grep,Glob\" \"Find all files that import the auth module\"\n\n# Skip permissions (sandboxed environments only)\nclaude -p --dangerously-skip-permissions \"Fix all lint errors in src/\"\n```\n\n### Parallel Background Execution\n\n```bash\n# Spawn multiple headless instances in parallel\nclaude -p \"Analyze src/auth/ for vulnerabilities\" &\nclaude -p \"Write tests for src/api/endpoints.ts\" &\nclaude -p \"Review src/models/ for performance issues\" &\nwait  # Wait for all to complete\n\n# With results captured\nSECURITY=$(claude -p \"Security audit of auth module\" &)\nTESTS=$(claude -p \"Generate test coverage report\" &)\nPERF=$(claude -p \"Profile memory usage in workers\" &)\nwait\necho \"$SECURITY\" \"$TESTS\" \"$PERF\"\n```\n\n### Session Continuation\n\n```bash\n# Start a task, resume later\nclaude -p --session-id \"abc-123\" \"Start analyzing the codebase\"\nclaude -p --resume \"abc-123\" \"Continue with the test files\"\n\n# Fork a session for parallel exploration\nclaude -p --resume \"abc-123\" --fork-session \"Try approach A: event sourcing\"\nclaude -p --resume \"abc-123\" --fork-session \"Try approach B: CQRS pattern\"\n```\n\n### Key Flags\n\n| Flag | Purpose |\n|------|---------|\n| `-p, --print` | Non-interactive mode, print and exit |\n| `--model <model>` | Select model (haiku, sonnet, opus) |\n| `--output-format <fmt>` | Output: text, json, stream-json |\n| `--max-budget-usd <amt>` | Spending cap per invocation |\n| `--allowedTools <tools>` | Restrict available tools |\n| `--append-system-prompt` | Add custom instructions |\n| `--resume <id>` | Continue a previous session |\n| `--fork-session` | Branch from resumed session |\n| `--fallback-model <model>` | Auto-fallback if primary overloaded |\n| `--permission-mode <mode>` | acceptEdits, bypassPermissions, plan, etc. |\n| `--mcp-config <json>` | Load MCP servers from JSON |\n\n## Available Agents (60+ Types)\n\n### Core Development\n`coder`, `reviewer`, `tester`, `planner`, `researcher`\n\n### V3 Specialized Agents\n`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`\n\n### @claude-flow/security Module\nCVE remediation, input validation, path security:\n- `InputValidator` — Zod-based validation at boundaries\n- `PathValidator` — Path traversal prevention\n- `SafeExecutor` — Command injection protection\n- `PasswordHasher` — bcrypt hashing\n- `TokenGenerator` — Secure token generation\n\n### Token Optimizer (Agent Booster)\nIntegrates agentic-flow optimizations for 30-50% token reduction:\n```typescript\nimport { getTokenOptimizer } from '@claude-flow/integration';\nconst optimizer = await getTokenOptimizer();\n\n// Compact context (32% fewer tokens)\nconst ctx = await optimizer.getCompactContext(\"auth patterns\");\n\n// 352x faster edits = fewer retries\nawait optimizer.optimizedEdit(file, old, new, \"typescript\");\n\n// Optimal config (100% success rate)\nconst config = optimizer.getOptimalConfig(agentCount);\n```\n| Feature | Token Savings |\n|---------|---------------|\n| ReasoningBank retrieval | -32% |\n| Agent Booster edits | -15% |\n| Cache (95% hit rate) | -10% |\n| Optimal batch size | -20% |\n\n### Swarm Coordination\n`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`, `collective-intelligence-coordinator`, `swarm-memory-manager`\n\n### Consensus & Distributed\n`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`, `consensus-builder`, `crdt-synchronizer`, `quorum-manager`, `security-manager`\n\n### Performance & Optimization\n`perf-analyzer`, `performance-benchmarker`, `task-orchestrator`, `memory-coordinator`, `smart-agent`\n\n### GitHub & Repository\n`github-modes`, `pr-manager`, `code-review-swarm`, `issue-tracker`, `release-manager`, `workflow-automation`, `project-board-sync`, `repo-architect`, `multi-repo-swarm`\n\n### SPARC Methodology\n`sparc-coord`, `sparc-coder`, `specification`, `pseudocode`, `architecture`, `refinement`\n\n### Specialized Development\n`backend-dev`, `mobile-dev`, `ml-developer`, `cicd-engineer`, `api-docs`, `system-architect`, `code-analyzer`, `base-template-generator`\n\n### Testing & Validation\n`tdd-london-swarm`, `production-validator`\n\n## Agent Teams & Comms System\n\nAgent 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.\n\n### Architecture\n\n```\nTeam Lead (you)\n  ├── SendMessage ←→ architect (named agent)\n  ├── SendMessage ←→ developer (named agent)\n  ├── SendMessage ←→ tester (named agent)\n  └── SendMessage ←→ reviewer (named agent)\n       ↕ agents can message each other by name\n```\n\n### Core Principle: Named Agents + SendMessage\n\nEvery agent MUST have a `name` so it's addressable. Communication happens via `SendMessage`, not polling or shared memory.\n\n```javascript\n// STEP 1: Spawn named agents (all in ONE message, background)\nTask({\n  prompt: \"Design the API. When done, send your design to 'developer' via SendMessage.\",\n  subagent_type: \"system-architect\",\n  name: \"architect\",\n  run_in_background: true\n})\nTask({\n  prompt: \"Wait for architect's design via SendMessage. Then implement it. Send code to 'tester'.\",\n  subagent_type: \"coder\",\n  name: \"developer\",\n  run_in_background: true\n})\nTask({\n  prompt: \"Wait for developer's code via SendMessage. Write tests. Send results to 'reviewer'.\",\n  subagent_type: \"tester\",\n  name: \"tester\",\n  run_in_background: true\n})\n\n// STEP 2: Kick off the pipeline by messaging the first agent\nSendMessage({\n  to: \"architect\",\n  summary: \"Start API design\",\n  message: \"Design a REST API for user management with CRUD endpoints. Send the design to 'developer' when done.\"\n})\n```\n\n### SendMessage Protocol\n\n```javascript\n// Lead → Teammate: assign work\nSendMessage({ to: \"developer\", summary: \"Implement auth\", message: \"Build OAuth2 flow...\" })\n\n// Lead → Teammate: redirect priorities\nSendMessage({ to: \"developer\", summary: \"Prioritize auth\", message: \"Auth endpoint is blocking tester, do it first.\" })\n\n// Lead → Teammate: provide context from another agent's results\nSendMessage({ to: \"tester\", summary: \"Architect output\", message: \"The architect designed these endpoints: [details]. Write tests for them.\" })\n\n// Lead → Teammate: graceful shutdown\nSendMessage({ to: \"developer\", message: { type: \"shutdown_request\" } })\n```\n\n### Coordination Patterns\n\n**Pipeline (A → B → C)** — each agent messages the next when done:\n```\narchitect ──SendMessage──→ developer ──SendMessage──→ tester ──SendMessage──→ reviewer\n```\nTell each agent WHO to message next in their prompt.\n\n**Fan-out / Fan-in** — lead spawns parallel agents, collects results:\n```\n         ┌→ researcher-1 ──→┐\nlead ────┼→ researcher-2 ──→├──→ lead synthesizes\n         └→ researcher-3 ──→┘\n```\nSpawn with `run_in_background: true`. Results arrive as task completions.\n\n**Supervisor / Worker** — lead assigns, workers report back:\n```\nlead ←──SendMessage──→ worker-1\nlead ←──SendMessage──→ worker-2\nlead ←──SendMessage──→ worker-3\n```\nLead sends tasks via SendMessage, workers respond with results.\n\n### Agent Prompt Template (Comms-Aware)\n\nWhen spawning agents that need to coordinate, include comms instructions:\n\n```javascript\nTask({\n  prompt: `You are the architect for this feature team.\n\nYOUR TASK: Design the database schema for user management.\n\nCOMMS PROTOCOL:\n- When your design is ready, send it to \"developer\" via SendMessage\n- If you need clarification, message the team lead (just output text)\n- Include file paths and key decisions in your message\n\nDELIVERABLE: Schema design with entity relationships, indexes, and migration plan.`,\n  subagent_type: \"system-architect\",\n  name: \"architect\",\n  run_in_background: true\n})\n```\n\n### Full Team Spawn Example\n\n```javascript\n// Create shared task list first\nTaskCreate({ subject: \"Design schema\", description: \"...\", activeForm: \"Designing\" })\nTaskCreate({ subject: \"Implement models\", description: \"...\", activeForm: \"Implementing\" })\nTaskCreate({ subject: \"Write tests\", description: \"...\", activeForm: \"Testing\" })\nTaskCreate({ subject: \"Security review\", description: \"...\", activeForm: \"Reviewing\" })\n\n// Spawn ALL named agents in ONE message\nTask({\n  prompt: \"Design the schema. SendMessage to 'developer' with your design when done. Update task #1.\",\n  subagent_type: \"system-architect\", name: \"architect\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for schema from 'architect'. Implement models + endpoints. SendMessage to 'tester'. Update task #2.\",\n  subagent_type: \"coder\", name: \"developer\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for code from 'developer'. Write integration tests. SendMessage results to 'security'. Update task #3.\",\n  subagent_type: \"tester\", name: \"tester\", run_in_background: true\n})\nTask({\n  prompt: \"Wait for test results from 'tester'. Review for vulnerabilities. Update task #4.\",\n  subagent_type: \"security-auditor\", name: \"security\", run_in_background: true\n})\n```\n\n### Agent Teams Hooks\n\n| Hook | Trigger | Purpose |\n|------|---------|---------|\n| `TeammateIdle` | Teammate finishes turn | Auto-assign pending tasks via SendMessage |\n| `TaskCompleted` | Task marked complete | Train patterns, notify lead via SendMessage |\n\n```bash\nnpx claude-flow@v3alpha hooks teammate-idle --auto-assign true\nnpx claude-flow@v3alpha hooks task-completed -i task-123 --train-patterns true\n```\n\n### Rules\n\n1. **Always name agents** — use `name: \"role-name\"` so they're addressable\n2. **Comms over memory** — use SendMessage for real-time coordination, memory for persistence\n3. **Pipeline prompts** — tell each agent WHO to message next and WHAT to send\n4. **Spawn all at once** — all Task calls in ONE message with `run_in_background: true`\n5. **Don't poll** — agents message back when done; wait for task completion notifications\n6. **Graceful shutdown** — send `{ type: \"shutdown_request\" }` before TeamDelete\n7. **Lead synthesizes** — when agents complete, review ALL results before responding to user\n\n## V3 Hooks System (17 Hooks + 12 Workers)\n\n### Hook Categories\n\n| Category | Hooks | Purpose |\n|----------|-------|---------|\n| **Core** | `pre-edit`, `post-edit`, `pre-command`, `post-command`, `pre-task`, `post-task` | Tool lifecycle |\n| **Session** | `session-start`, `session-end`, `session-restore`, `notify` | Context management |\n| **Intelligence** | `route`, `explain`, `pretrain`, `build-agents`, `transfer` | Neural learning |\n| **Learning** | `intelligence` (trajectory-start/step/end, pattern-store/search, stats, attention) | Reinforcement |\n| **Agent Teams** | `teammate-idle`, `task-completed` | Multi-agent coordination |\n\n### 12 Background Workers\n\n| Worker | Priority | Description |\n|--------|----------|-------------|\n| `ultralearn` | normal | Deep knowledge acquisition |\n| `optimize` | high | Performance optimization |\n| `consolidate` | low | Memory consolidation |\n| `predict` | normal | Predictive preloading |\n| `audit` | critical | Security analysis |\n| `map` | normal | Codebase mapping |\n| `preload` | low | Resource preloading |\n| `deepdive` | normal | Deep code analysis |\n| `document` | normal | Auto-documentation |\n| `refactor` | normal | Refactoring suggestions |\n| `benchmark` | normal | Performance benchmarking |\n| `testgaps` | normal | Test coverage analysis |\n\n### Essential Hook Commands\n\n```bash\n# Core hooks\nnpx claude-flow@v3alpha hooks pre-task --description \"[task]\"\nnpx claude-flow@v3alpha hooks post-task --task-id \"[id]\" --success true\nnpx claude-flow@v3alpha hooks post-edit --file \"[file]\" --train-patterns\n\n# Session management\nnpx claude-flow@v3alpha hooks session-start --session-id \"[id]\"\nnpx claude-flow@v3alpha hooks session-end --export-metrics true\nnpx claude-flow@v3alpha hooks session-restore --session-id \"[id]\"\n\n# Intelligence routing\nnpx claude-flow@v3alpha hooks route --task \"[task]\"\nnpx claude-flow@v3alpha hooks explain --topic \"[topic]\"\n\n# Neural learning\nnpx claude-flow@v3alpha hooks pretrain --model-type moe --epochs 10\nnpx claude-flow@v3alpha hooks build-agents --agent-types coder,tester\n\n# Background workers\nnpx claude-flow@v3alpha hooks worker list\nnpx claude-flow@v3alpha hooks worker dispatch --trigger audit\nnpx claude-flow@v3alpha hooks worker status\n```\n\n## Intelligence System (RuVector)\n\nV3 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)):\n- **SONA**: Self-Optimizing Neural Architecture (measured 0.0043ms/adapt, target <0.05ms met)\n- **MoE**: Mixture of Experts for specialized routing (gate converges — confidence 0.13→0.88 after rewards)\n- **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)\n- **EWC++**: Elastic Weight Consolidation (prevents forgetting)\n- **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)\n\nThe 4-step intelligence pipeline:\n1. **RETRIEVE** — Fetch relevant patterns via HNSW\n2. **JUDGE** — Evaluate with verdicts (success/failure)\n3. **DISTILL** — Extract key learnings via LoRA\n4. **CONSOLIDATE** — Prevent catastrophic forgetting via EWC++\n\n## Embeddings Package (v3.0.0-alpha.12)\n\nFeatures:\n- **sql.js**: Cross-platform SQLite persistent cache (WASM, no native compilation)\n- **Document chunking**: Configurable overlap and size\n- **Normalization**: L2, L1, min-max, z-score\n- **Hyperbolic embeddings**: Poincare ball model for hierarchical data\n- **agentic-flow ONNX integration**: speedup unverified (no benchmark; backend reported `onnx`, model all-MiniLM-L6-v2, 384-dim)\n- **Neural substrate**: Integration with RuVector\n\n## Hive-Mind Consensus\n\n### Topologies\n- `hierarchical` — Queen controls workers directly\n- `mesh` — Fully connected peer network\n- `hierarchical-mesh` — Hybrid (recommended)\n- `adaptive` — Dynamic based on load\n\n### Consensus Strategies\n- `byzantine` — BFT (tolerates f < n/3 faulty)\n- `raft` — Leader-based (tolerates f < n/2)\n- `gossip` — Epidemic for eventual consistency\n- `crdt` — Conflict-free replicated data types\n- `quorum` — Configurable quorum-based\n\n## V3 Performance Targets\n\n> 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\".\n\n| Metric | Measured / Target | Status |\n|--------|-------------------|--------|\n| 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) |\n| Int8 Quantization | 3.84x compression, reconstruction cosine 0.99999 | **Measured** |\n| RaBitQ Quantization | 32x compression, 0.60ms/query (14,760-vec index) | **Measured** |\n| SONA Adaptation | 0.0043ms/adapt (target <0.05ms met) | **Measured** |\n| MoE Gate | converges — confidence 0.13→0.88, Q 0→99.8 after rewards | **Measured** |\n| 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 |\n| MCP Response | <100ms | target |\n| CLI Startup | <500ms | target |\n\n## Environment Variables\n\n```bash\n# Configuration\nCLAUDE_FLOW_CONFIG=./claude-flow.config.json\nCLAUDE_FLOW_LOG_LEVEL=info\n\n# Provider API Keys\nANTHROPIC_API_KEY=sk-ant-...\nOPENAI_API_KEY=sk-...\nGOOGLE_API_KEY=...\n\n# MCP Server\nCLAUDE_FLOW_MCP_PORT=3000\nCLAUDE_FLOW_MCP_HOST=localhost\nCLAUDE_FLOW_MCP_TRANSPORT=stdio\n\n# Memory\nCLAUDE_FLOW_MEMORY_BACKEND=hybrid\nCLAUDE_FLOW_MEMORY_PATH=./data/memory\n```\n\n## Doctor Health Checks\n\nRun `npx claude-flow@v3alpha doctor` to check:\n- Node.js version (20+)\n- npm version (9+)\n- Git installation\n- Config file validity\n- Daemon status\n- Memory database\n- API keys\n- MCP servers\n- Disk space\n- TypeScript installation\n\n## Quick Setup\n\n```bash\n# Add MCP servers\nclaude mcp add claude-flow -- npx -y ruflo@latest mcp start\nclaude mcp add ruv-swarm npx ruv-swarm mcp start  # Optional\nclaude mcp add flow-nexus npx flow-nexus@latest mcp start  # Optional\n\n# Start daemon\nnpx claude-flow@v3alpha daemon start\n\n# Run doctor\nnpx claude-flow@v3alpha doctor --fix\n```\n\n## Claude Code vs MCP Tools\n\n### Claude Code Handles ALL EXECUTION:\n- **Task tool**: Spawn and run agents concurrently\n- File operations (Read, Write, Edit, MultiEdit, Glob, Grep)\n- Code generation and programming\n- Bash commands and system operations\n- TodoWrite and task management\n- Git operations\n\n### MCP Tools ONLY COORDINATE:\n- Swarm initialization (topology setup)\n- Agent type definitions\n- Task orchestration\n- Memory management\n- Neural features\n- Performance tracking\n\n- Keep MCP for coordination strategy only — use Claude Code's Task tool for real execution\n\n## Claude Code ↔ AgentDB Memory Bridge\n\nClaude Code's auto-memory (`~/.claude/projects/*/memory/*.md`) is bridged to AgentDB with ONNX vector embeddings for semantic search.\n\n### MCP Tools\n\n| Tool | Description |\n|------|-------------|\n| `memory_import_claude` | Import Claude Code memories into AgentDB with 384-dim ONNX embeddings. Use `allProjects: true` to import from ALL projects. |\n| `memory_bridge_status` | Show bridge health — Claude files, AgentDB entries, SONA state, connection status |\n| `memory_search_unified` | Semantic search across ALL namespaces (claude-memories, auto-memory, patterns, tasks, feedback) |\n\n### Auto-Import on Session Start\n\nThe `SessionStart` hook automatically imports current project's memories into AgentDB. For manual import of all projects:\n\n```bash\n# Via MCP tool (from Claude Code)\nmemory_import_claude({ allProjects: true })\n\n# Via helper hook (from terminal)\nnode .claude/helpers/auto-memory-hook.mjs import-all\n```\n\n### Unified Search\n\nSearch across both Claude Code memories and AgentDB entries:\n\n```bash\n# Via MCP tool\nmemory_search_unified({ query: \"authentication security\", limit: 5 })\n\n# Results include source attribution: claude-code, auto-memory, or agentdb\n```\n\n### Intelligence Pipeline\n\n| Component | Status | Details |\n|-----------|--------|---------|\n| ONNX Embeddings | Active | all-MiniLM-L6-v2, 384 dimensions |\n| SONA Learning | Active | Pattern matching + trajectory recording |\n| ReasoningBank | Active | Pattern storage with file persistence |\n| AgentDB sql.js | Active | SQLite with vector_indexes table |\n\n## Publishing to npm\n\n### Versioning policy (stable releases — alpha series ended at 3.7.0-alpha.81, 2026-05-23)\n\n- **From 3.7.0 onward we ship stable semver**, NOT alpha pre-releases.\n- Bump rules (semver discipline):\n  - **PATCH** (3.7.0 → 3.7.1): bug fixes only, no API change, no schema change\n  - **MINOR** (3.7.0 → 3.8.0): backward-compatible additions (new MCP tool, new flag, new agent type)\n  - **MAJOR** (3.x → 4.0.0): breaking change in CLI surface, MCP tool signature, file layout, or default behavior\n- 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`.\n- Never publish a pre-release (`-alpha.N`, `-beta.N`, `-rc.N`) unless the user explicitly asks for a pre-release flow.\n\n### Publishing Rules\n\n- The normal public release train is exactly THREE packages:\n  `@claude-flow/cli`, `claude-flow`, and `ruflo`.\n- Internal `@claude-flow/*` components are bundled into the public artifacts;\n  do not publish them standalone as part of the normal release.\n- MUST update ALL dist-tags for ALL THREE packages after publishing (latest + alpha + v3alpha all point to the same version)\n- Publish order: `@claude-flow/cli` first, then `claude-flow` (umbrella), then `ruflo` (alias umbrella)\n- MUST run verification for ALL THREE before telling user publishing is complete\n- Run `node scripts/audit-umbrella-version-lockstep.mjs` before packing or\n  publishing.\n- Publish from a clean reviewed commit/tag-equivalent worktree. Do not ship\n  unrelated uncommitted changes.\n- A fresh worktree has two separate dependency trees to install before anything\n  builds: `npm install` at repo root (npm workspaces), AND `pnpm install` inside\n  `v3/` (a separate pnpm workspace — root `prepare-root-publish.mjs` shells out to\n  `pnpm --filter` to build `v3/@claude-flow/{shared,hooks,guidance}`, which fails\n  with `spawn ENOENT` on `tsc` if `v3/node_modules` was never populated).\n- Use the existing authenticated `ruvnet` npm session. Do not replace it with a\n  token from another GCP project.\n\n**`npm publish` auth — FIXED (2026-07-30):** use the `NPM_TOKEN` secret directly,\nvia a throwaway `.npmrc` with `NPM_CONFIG_USERCONFIG` — same pattern as the\nhelpers-signing-key handling. It is mirrored in two GCP projects — `ruv-dev`\n(version 3+) and `cognitum-20260110` (version 7+) — so either project's copy\nis current; use whichever `gcloud` session is already authenticated. This is a\ngranular access token (\"ruflo publishjing\", expires 2026-10-28) with\n`package: write` + `bypass_2fa: true`, scoped broadly enough to cover\n`@claude-flow/cli`, `claude-flow`, and `ruflo` (plus the `cognitum`/\n`cognitum-one` orgs). Confirmed end-to-end against the real registry (not just\na permissions probe): `npm publish` for `@claude-flow/cli` succeeded via this\ntoken with zero OTP/WebAuthn prompt, and\n`npm dist-tag add` against both a scoped (`@claude-flow/cli`) and unscoped\n(`claude-flow`) package also went through with no prompt.\n\n**Why the earlier `NPM_TOKEN` version failed:** versions 1/2 of that secret\nwere older classic automation tokens, and npm has been restricting tokens that\nbypass 2FA for writes account-wide (the login flow prints this notice —\n`gh.io/npm-gat-bypass2fa-deprecation`). Version 3 is a **granular access\ntoken** created explicitly for this purpose, which is npm's supported\nreplacement path (its own 2FA-bypass flag still works for a granular token,\nunlike the deprecated classic automation tokens). If this token's `bypass_2fa`\nflag or scope ever gets narrowed/expired (check expiry above), the fallback\nis the WebAuthn dance below — but try this path first every time.\n\n```bash\ngcloud secrets versions access latest --secret=NPM_TOKEN --project=ruv-dev > /tmp/.npmrc-publish-raw\nprintf '//registry.npmjs.org/:_authToken=%s\\n' \"$(cat /tmp/.npmrc-publish-raw)\" > /tmp/.npmrc-publish\nrm -f /tmp/.npmrc-publish-raw\nNPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm publish   # from the package dir, with signing-key env vars for @claude-flow/cli\nNPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> alpha\nNPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> v3alpha\nshred -u /tmp/.npmrc-publish 2>/dev/null || rm -f /tmp/.npmrc-publish   # ALWAYS clean up, same discipline as the signing key\n```\n\n**Fallback — WebAuthn procedure, if the token above is dead:** the `ruvnet`\naccount's 2FA method is a WebAuthn security key, not TOTP (no numeric\n`--otp=<code>` exists). This must be driven by the human (an agent cannot\napprove a WebAuthn browser prompt):\n1. Human goes to npmjs.com → account 2FA settings → turns OFF \"Require\n   two-factor authentication for write actions\" (narrows to auth-only, not a\n   full 2FA disable), then runs `npm login` in their own terminal to refresh\n   the session under the new setting.\n2. Agent can then run `npm publish` directly via Bash with no further prompt.\n3. **`npm dist-tag add` still requires a fresh WebAuthn approval PER CALL**\n   regardless of the write-2FA setting — 6 individual browser approvals for a\n   3-package release (alpha + v3alpha × 3), not 1. Tell the human up front.\n- After every dist-tag call (or if unsure), verify with\n  `npm view <pkg> dist-tags --json` — don't trust the CLI's own stdout alone, since\n  a WebAuthn prompt that's still pending in the browser produces no terminal\n  output an agent can see.\n- Confirm the version actually landed (`npm view <pkg>@<version> version`) before\n  telling the user publishing succeeded, same reasoning: a mid-publish approval\n  that never gets answered fails silently from an agent's point of view.\n\n**Helpers signing key (required for `@claude-flow/cli` publish):** `npm publish`'s\n`prepublishOnly` runs `scripts/sign-helpers.mjs`, which needs a private key to sign\n`.claude/helpers/helpers.manifest.json`. The secret lives in GCP Secret Manager in the\n**`ruv-dev`** project (not `cognitum-20260110` or `claude-flow` — checked both, not there),\nsecret name `ruflo-helpers-signing-key`:\n\n```bash\ncd v3/@claude-flow/cli\nRUFLO_HELPERS_SIGNING_SECRET=ruflo-helpers-signing-key RUFLO_HELPERS_SIGNING_PROJECT=ruv-dev \\\n  npm publish\n```\n\n(`ruv-dev` also holds `ruflo-config-signing-key`; do not replace the existing\nauthenticated npm session with a token from another project.)\n\n**Handling the signing key without leaking it (learned 2026-07-14, hard way):**\nan earlier Windows path invoked `gcloud` without its required `.cmd` suffix. The\nfallback command printed the PEM into captured tool output and a session transcript.\nGCP secret v1 was destroyed and a fresh v2 was rotated in (commit 0052b1b06 /\nPR #2673). `sign-helpers.mjs` now selects `gcloud.cmd` on Windows and supports a\nstdin-only fallback. **Rules:**\n- NEVER invoke `gcloud secrets versions access` in a way that lets the payload reach\n  tool output. Use the built-in `RUFLO_HELPERS_SIGNING_SECRET` path above, or pipe\n  directly into the signer:\n  `gcloud secrets versions access latest --secret=ruflo-helpers-signing-key --project=ruv-dev | node scripts/sign-helpers.mjs --stdin-key`.\n- `--stdin-key` refuses interactive entry, validates Ed25519 key type, and never\n  echoes parser input. A local file via `RUFLO_HELPERS_SIGNING_KEY` remains the\n  air-gapped fallback.\n- If a rotation IS needed, keep the private half in `~/.ruflo/helpers-signing.key`\n  only, print ONLY the public half (via `Ed25519 pub export` from Node crypto), upload\n  new private via `gcloud secrets versions add … --data-file=`, then\n  `gcloud secrets versions destroy <old>` to make the old irrecoverable.\n\n**Windows `prepublishOnly` failure (learned 2026-07-14):** the CLI's `prepublishOnly`\nchain (`cp ../../../README.md ./README.md && rm -rf plugins && mkdir -p plugins && cp -r ...`)\nis POSIX-shell-only. On Windows, npm runs it via `cmd.exe /d /s /c` which chokes on\n`mkdir -p` (interprets `-p` as a directory name) and `cp -r` (no such command). Two\nworkarounds until the script is rewritten in cross-platform Node:\n1. Run the prep steps manually in Git Bash, then `npm publish --ignore-scripts`.\n2. Or use a POSIX shell for the whole publish: `SHELL=bash npm publish` — but this\n   doesn't always take effect on Windows depending on npm version.\nOption 1 is what worked for v3.29.0. Track proper fix in ruvnet/ruflo issue for\ncross-platform prepublish.\n\n**Concurrent-session helper corruption (real, observed, be paranoid):** multiple Claude Code\nsessions can have their own `npm exec @claude-flow/cli@latest mcp start` MCP server running\nconcurrently with `cwd` inside this repo (check with `readlink /proc/<pid>/cwd` on\n`pgrep -f \"npm exec @claude-flow/cli@latest mcp start\"`). If one of those resolved an older\ncached `@latest` (predating the `semver.gte` downgrade-guard in\n`helper-refresh.ts:autoRefreshHelpersIfStale`), it will silently overwrite this repo's\nhand-maintained `.claude/helpers/hook-handler.cjs` / `intelligence.cjs` (root AND package\ncopies) — and `helpers.manifest.json` + `.helpers-version` — with its own older bundled\ncontent, mid-session, with no warning. Observed live 2026-07-13: this happened *twice* in\none publish flow, once right after a manual revert and once right after signing (silently\ninvalidating a freshly-signed manifest). **Mitigation:** never trust the on-disk state of\nthose files between tool calls — `git diff --stat` them immediately before any `git add`/\n`sign-helpers.mjs`/`npm publish` step, `git checkout HEAD --` revert if dirty, and chain\nrevert → sign → verify → add → commit as ONE bash invocation (`&&`-joined) to minimize the\nrace window. `npm publish`'s own `prepublishOnly` re-signs fresh at pack time regardless, so\nwhat matters is the on-disk state at the *exact moment* `npm publish` runs, not before.\n\n```bash\n# Replace 3.7.1 below with your chosen stable version (patch/minor/major per the rules above)\n\n# STEP 1: Build and publish @claude-flow/cli\ncd v3/@claude-flow/cli\nnpm version 3.7.1 --no-git-tag-version\nnpm run build\nnpm publish                              # default tag is `latest` — no --tag flag\nnpm dist-tag add @claude-flow/cli@3.7.1 alpha     # historical compat\nnpm dist-tag add @claude-flow/cli@3.7.1 v3alpha   # historical compat\n\n# STEP 2: Publish claude-flow umbrella\ncd /Users/cohen/Projects/ruflo                    # or your repo root\nnpm version 3.7.1 --no-git-tag-version\nnpm publish\nnpm dist-tag add claude-flow@3.7.1 alpha\nnpm dist-tag add claude-flow@3.7.1 v3alpha\n\n# STEP 3: Publish ruflo wrapper (CRITICAL — DON'T FORGET — this is what users run)\ncd ruflo\nnpm version 3.7.1 --no-git-tag-version\nnpm publish\nnpm dist-tag add ruflo@3.7.1 alpha\nnpm dist-tag add ruflo@3.7.1 v3alpha\n```\n\n**Verification (run before telling user publishing is complete):**\n\n```bash\nfor pkg in @claude-flow/cli claude-flow ruflo; do\n  echo \"$pkg: $(npm view $pkg@latest version)\"\n  npm view $pkg dist-tags --json\ndone\n# All three must show latest === alpha === v3alpha === new version\n```\n\n### All Tags That Must Be Updated\n\n| Package | Tag | Command Users Run |\n|---------|-----|-------------------|\n| `@claude-flow/cli` | `latest` | `npx @claude-flow/cli@latest` |\n| `@claude-flow/cli` | `alpha` | `npx @claude-flow/cli@alpha` (legacy compat) |\n| `@claude-flow/cli` | `v3alpha` | `npx @claude-flow/cli@v3alpha` (legacy compat) |\n| `claude-flow` | `latest` | `npx claude-flow@latest` |\n| `claude-flow` | `alpha` | `npx claude-flow@alpha` (legacy compat) |\n| `claude-flow` | `v3alpha` | `npx claude-flow@v3alpha` (legacy compat) |\n| `ruflo` | `latest` | `npx ruflo@latest` |\n| `ruflo` | `alpha` | `npx ruflo@alpha` (legacy compat) |\n| `ruflo` | `v3alpha` | `npx ruflo@v3alpha` (legacy compat) |\n\n- Never forget the `ruflo` package — it's the thin wrapper users actually run via `npx ruflo`\n- The legacy `alpha` and `v3alpha` tags MUST stay pointed at the latest stable so old install commands keep working\n- `ruflo` source is in `/ruflo/` — it depends on `@claude-flow/cli`\n- 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)\n\n### GitHub Release after publish\n\nEvery stable bump SHOULD have a matching `gh release create v<version>` with consolidated release notes pointing at the gist if one exists. Example:\n\n```bash\ngit tag v3.7.1 main\ngit push origin v3.7.1\ngh release create v3.7.1 --title \"v3.7.1 — <one-line headline>\" \\\n  --notes-file /tmp/release-notes.md\n```\n\n## Plugin Registry Maintenance (IPFS/Pinata)\n\nThe plugin registry is stored on IPFS via Pinata for decentralized, immutable distribution.\n\n### Registry Location\n- **Current CID**: Stored in `v3/@claude-flow/cli/src/plugins/store/discovery.ts`\n- **Gateway**: `https://gateway.pinata.cloud/ipfs/{CID}`\n- **Format**: JSON with plugin metadata, categories, featured/trending lists\n\n### Required Environment Variables\nAdd to `.env` (NEVER commit actual values):\n```bash\nPINATA_API_KEY=your-api-key\nPINATA_API_SECRET=your-api-secret\nPINATA_API_JWT=your-jwt-token\n```\n\n## Plugin Registry Operations\n\n### Adding a New Plugin to Registry\n\n1. **Fetch current registry**:\n```bash\ncurl -s \"https://gateway.pinata.cloud/ipfs/$(grep LIVE_REGISTRY_CID v3/@claude-flow/cli/src/plugins/store/discovery.ts | cut -d\"'\" -f2)\" > /tmp/registry.json\n```\n\n2. **Add plugin entry** to the `plugins` array:\n```json\n{\n  \"id\": \"@claude-flow/your-plugin\",\n  \"name\": \"@claude-flow/your-plugin\",\n  \"displayName\": \"Your Plugin\",\n  \"description\": \"Plugin description\",\n  \"version\": \"1.0.0-alpha.1\",\n  \"size\": 100000,\n  \"checksum\": \"sha256:abc123\",\n  \"author\": {\"id\": \"claude-flow-team\", \"displayName\": \"Claude Flow Team\", \"verified\": true},\n  \"license\": \"MIT\",\n  \"categories\": [\"official\"],\n  \"tags\": [\"your\", \"tags\"],\n  \"downloads\": 0,\n  \"rating\": 5,\n  \"lastUpdated\": \"2026-01-25T00:00:00.000Z\",\n  \"minClaudeFlowVersion\": \"3.0.0\",\n  \"type\": \"integration\",\n  \"hooks\": [],\n  \"commands\": [],\n  \"permissions\": [\"memory\"],\n  \"exports\": [\"YourExport\"],\n  \"verified\": true,\n  \"trustLevel\": \"official\"\n}\n```\n\n3. **Update counts and arrays**:\n   - Increment `totalPlugins`\n   - Add to `official` array\n   - Add to `featured`/`newest` if applicable\n   - Update category `pluginCount`\n\n4. **Upload to Pinata** (read credentials from .env):\n```bash\n# Source credentials from .env\nPINATA_JWT=$(grep \"^PINATA_API_JWT=\" .env | cut -d'=' -f2-)\n\n# Upload updated registry\ncurl -X POST \"https://api.pinata.cloud/pinning/pinJSONToIPFS\" \\\n  -H \"Authorization: Bearer $PINATA_JWT\" \\\n  -H \"Content-Type: application/json\" \\\n  -d @/tmp/registry.json\n```\n\n5. **Update discovery.ts** with new CID:\n```typescript\nexport const LIVE_REGISTRY_CID = 'NEW_CID_FROM_PINATA';\n```\n\n6. **Also update demo registry** in discovery.ts `demoPluginRegistry` for offline fallback\n\n### Security Rules\n- NEVER hardcode API keys in scripts or source files\n- NEVER commit .env (already in .gitignore)\n- Always source credentials from environment at runtime\n- Always delete temporary scripts after one-time uploads\n\n### Verification\n```bash\n# Verify new registry is accessible\ncurl -s \"https://gateway.pinata.cloud/ipfs/{NEW_CID}\" | jq '.totalPlugins'\n```\n\n## MetaHarness Integration (ADR-150)\n\nRuflo 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.\n\n### Architectural constraint (load-bearing)\n\n**Ruflo remains operational if every MetaHarness package is removed.** Four rules:\n1. **Removable**: `npm ls --without @metaharness/*` must still produce a working CLI\n2. **Optional in package.json**: `@metaharness/*` packages MUST be optional peers, never normal dependencies\n3. **Graceful degradation**: every code path that touches MetaHarness catches `MODULE_NOT_FOUND` and falls back\n4. **CI gate**: `.github/workflows/no-metaharness-smoke.yml` enforces all three by static grep + runtime drill on every PR\n\n### Command + tool surface\n\n```bash\n# CLI subcommands (npx ruflo metaharness …)\nnpx ruflo metaharness score                      # 5-dim readiness scorecard\nnpx ruflo metaharness genome                     # 7-section categorical report\nnpx ruflo metaharness mcp-scan --fail-on high    # static security findings\nnpx ruflo metaharness threat-model               # enterprise threat report\nnpx ruflo metaharness oia-audit --alert-on-worst high\n                                                 # composite weekly audit → memory\nnpx ruflo metaharness audit-list --since 30d     # enumerate audit records\nnpx ruflo metaharness audit-trend \\              # diff two audits (drift)\n  --baseline-key <a> --current-key <b> --alert-on-worsening \\\n  --alert-on-distance-below 0.85               # iter 38 — structural-distance gate (ADR-152 §3.1)\nnpx ruflo metaharness similarity \\               # iter 36 — ADR-152 §3.1 weighted similarity\n  --a a.json --b b.json [--per-dimension] [--alert-below 0.5]\nnpx ruflo metaharness drift-from-history \\       # iter 53 — 1-command drift (composes 3 primitives)\n  [--baseline-since 7d] [--baseline-key <key>] [--baseline-file <path>] \\\n  [--threshold 0.95] [--alert-on-new-severity high] [--dry-run]\n                                                 # iter 66 — --baseline-key skips audit-list (~14x faster)\n                                                 # iter 67 — --baseline-file skips memory entirely (~19x faster)\n                                                 # iter 78 — --alert-on-new-severity adds orthogonal finding-severity gate\nnpx ruflo metaharness mint --name foo --template vertical:coding --confirm\nnpx ruflo metaharness redblue init               # @metaharness/redblue — scaffold redblue.yaml\nnpx ruflo metaharness redblue run --mock-judge --tests 10\n                                                 # $0 marker-fixture path (CI / offline)\nnpx ruflo metaharness redblue run --tests 50 --patch\n                                                 # real model judge (needs OPENROUTER_API_KEY,\n                                                 #   capped by max_cost_usd, default $3)\nnpx ruflo metaharness redblue attack prompt --count 3\n                                                 # preview generated attack cases (no target call)\nnpx ruflo metaharness redblue patch --mock-judge # baseline → blue-team patch → retest delta\nnpx ruflo metaharness redblue report --in report.json\n                                                 # render existing report as markdown\nnpx ruflo metaharness learn --host claude-code --model haiku --slice slices/lite.json\n                                                 # metaharness@0.3.0 / upstream ADR-235 —\n                                                 #   GEPA learning run; $0 dry-run default,\n                                                 #   --run to spend; needs a metaharness\n                                                 #   repo checkout (--repo / $METAHARNESS_REPO)\nnpx ruflo metaharness gepa --op genome           # darwin@0.8.0 GEPA library — load + validate\n                                                 #   the shipped cand-6 genome (or --path <f>)\nnpx ruflo metaharness gepa --op render           # genome → the system prompt it compiles to\nnpx ruflo metaharness gepa --op analyze --transcript run.json\n                                                 # classify failure modes in a transcript\nnpx ruflo metaharness evolve --bench .harness/bench.json\n                                                 # Darwin proposes candidates; governed gates decide\nnpx ruflo metaharness bench verify --path .harness/bench.json\n                                                 # create or verify stable benchmark corpora\nnpx ruflo metaharness flywheel run --proposer auto --max-concurrency 2\n                                                 # bounded concurrent evaluation; does not promote\nnpx ruflo metaharness flywheel receipts          # inspect immutable evaluation receipts\nnpx ruflo metaharness flywheel promote <receipt-id> \\\n  --public-key ./approved-ed25519-public.pem --confirm\n                                                 # explicit policy-authorized atomic promotion\n\n# Dedicated command\nnpx ruflo eject --name my-harness                # lift ruflo project → standalone harness\n                                                 # dry-run by default; refuses in-repo target\n\n# Doctor health check\nnpx ruflo doctor --component metaharness         # report metaharness availability + version\n\n# MCP tools (callable by Claude Code agents)\nmcp__claude-flow__metaharness_score\nmcp__claude-flow__metaharness_genome\nmcp__claude-flow__metaharness_mcp_scan\nmcp__claude-flow__metaharness_threat_model\nmcp__claude-flow__metaharness_oia_audit\nmcp__claude-flow__metaharness_audit_list\nmcp__claude-flow__metaharness_audit_trend\nmcp__claude-flow__metaharness_similarity          # iter 36 — ADR-152 §3.1 genome similarity\nmcp__claude-flow__metaharness_drift_from_history  # iter 53 — 1-command drift detection\nmcp__claude-flow__metaharness_bench               # ADR-153 — create/verify bench suites for evolve --bench\nmcp__claude-flow__metaharness_evolve              # MAP-Elites driver — evolve a harness across bench suites\nmcp__claude-flow__metaharness_security_bench      # security-focused benchmark suite gate\nmcp__claude-flow__metaharness_redblue             # @metaharness/redblue — adversarial red/blue LLM testing (init|run|patch|attack|report)\nmcp__claude-flow__metaharness_learn               # metaharness@0.3.0 — GEPA learning run ($0 dry-run default; run=true to spend)\nmcp__claude-flow__metaharness_gepa                # darwin@0.8.0 — GEPA genome ops (genome|validate|render|analyze); gepaOptimize stays library-only\nmcp__claude-flow__metaharness_flywheel            # ADR-322 — evaluate concurrently, inspect receipts/ledger, or explicitly promote\n```\n\n### Routing integration (ADR-148/149)\n\n`@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.\n\n### SelfEvolvingRouter parallel-logging (ADR-150 Phase 2)\n\nWhen `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:\n\n```bash\nnode plugins/ruflo-metaharness/scripts/router-parallel-analyze.mjs \\\n  --input .swarm/router-parallel.jsonl --strict\n```\n\nThe 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.\n\n### CI workflows\n\n- `metaharness-ci.yml` — score / mcp-scan / router-compat / eject-dryrun jobs on every PR touching `plugins/ruflo-metaharness/**`\n- `no-metaharness-smoke.yml` — enforces the four architectural-constraint rules above on every PR\n- `oia-audit-weekly.yml` — Sundays 04:17 UTC, runs composite audit, uploads 90-day artifact\n\n### Cross-references\n\n- [ADR-150](v3/docs/adr/ADR-150-metaharness-integration-surfaces.md) — decision + implementation notes\n- [Issue #2399](https://github.com/ruvnet/ruflo/issues/2399) — phase tracker\n- [Research gist](https://gist.github.com/ruvnet/19d166ff9acf368c9da4172d91ac9113) — graded evidence\n- Upstream: `github.com/ruvnet/agent-harness-generator`\n\n## Optional Plugins (20 Available)\n\nPlugins are distributed via IPFS and can be installed with the CLI. Browse and install from the official registry:\n\n```bash\n# List all available plugins\nnpx claude-flow@v3alpha plugins list\n\n# Install a plugin\nnpx claude-flow@v3alpha plugins install @claude-flow/plugin-name\n\n# Enable/disable\nnpx claude-flow@v3alpha plugins enable @claude-flow/plugin-name\nnpx claude-flow@v3alpha plugins disable @claude-flow/plugin-name\n```\n\n### Core Plugins\n\n| Plugin | Version | Description |\n|--------|---------|-------------|\n| `@claude-flow/embeddings` | 3.0.0-alpha.1 | Vector embeddings with sql.js, HNSW, hyperbolic support |\n| `@claude-flow/security` | 3.0.0-alpha.1 | Input validation, path security, CVE remediation |\n| `@claude-flow/claims` | 3.0.0-alpha.8 | Claims-based authorization (check, grant, revoke, list) |\n| `@claude-flow/neural` | 3.0.0-alpha.7 | Neural pattern training (SONA, MoE, EWC++) |\n| `@claude-flow/plugins` | 3.0.0-alpha.1 | Plugin system core (manager, discovery, store) |\n| `@claude-flow/performance` | 3.0.0-alpha.1 | Performance profiling and benchmarking |\n\n### Integration Plugins\n\n| Plugin | Version | Description |\n|--------|---------|-------------|\n| `@claude-flow/plugin-agentic-qe` | 3.0.0-alpha.4 | Agentic quality engineering integration |\n| `@claude-flow/plugin-prime-radiant` | 0.1.5 | Prime Radiant intelligence integration |\n| `@claude-flow/plugin-gastown-bridge` | 3.0.0-alpha.1 | Gastown bridge protocol integration |\n| `@claude-flow/teammate-plugin` | 1.0.0-alpha.1 | Multi-agent teammate coordination |\n| `@claude-flow/plugin-code-intelligence` | 0.1.0 | Advanced code analysis and intelligence |\n| `@claude-flow/plugin-test-intelligence` | 0.1.0 | Intelligent test generation and gap analysis |\n| `@claude-flow/plugin-perf-optimizer` | 0.1.0 | Performance optimization automation |\n| `@claude-flow/plugin-neural-coordinator` | 0.1.0 | Neural network coordination across agents |\n| `@claude-flow/plugin-cognitive-kernel` | 0.1.0 | Core cognitive processing kernel |\n| `@claude-flow/plugin-quantum-optimizer` | 0.1.0 | Quantum-inspired optimization algorithms |\n| `@claude-flow/plugin-hyperbolic-reasoning` | 0.1.0 | Hyperbolic space reasoning for hierarchical data |\n\n### Domain-Specific Plugins\n\n| Plugin | Version | Description |\n|--------|---------|-------------|\n| `@claude-flow/plugin-healthcare-clinical` | 0.1.0 | Healthcare clinical workflow automation |\n| `@claude-flow/plugin-financial-risk` | 0.1.0 | Financial risk assessment and modeling |\n| `@claude-flow/plugin-legal-contracts` | 0.1.0 | Legal contract analysis and generation |\n\n### Plugin Development\n\n```bash\n# Create a new plugin from template\nnpx claude-flow@v3alpha plugins create my-plugin\n\n# Test locally\nnpx claude-flow@v3alpha plugins install ./path/to/my-plugin\n\n# Publish to registry (requires Pinata credentials)\nnpx claude-flow@v3alpha plugins publish\n```\n\nRegistry source: IPFS via Pinata (`QmXbfEAaR7D2Ujm4GAkbwcGZQMHqAMpwDoje4583uNP834`)\n\n## Support\n\n- Documentation: https://github.com/ruvnet/claude-flow\n- Issues: https://github.com/ruvnet/claude-flow/issues\n\n---\n\nRemember: **Claude Flow coordinates, Claude Code creates!**\n\n## Gateway-Delegated Development (meta-llm dev-bridge)\n\nFor complex reasoning, architecture decisions, or hard bug-fixes, **delegate via the\n`metallm_delegate` MCP tool rather than solving inline.** The meta-llm gateway governs the\nwork: it routes cheap-tier-first, escalates genuinely-hard tasks to the frontier (Fable),\nand meters every call — so delegation is cost-governed and preserves the main session's context.\n\n- **Default to `cognitum-auto`** — the gateway picks the tier by difficulty. Only pass an\n  explicit tier (`cognitum-low|mid|high`) when you must force one.\n- Prompt-wrapping does **not** inflate cost — the gateway normalizes host scaffolds so an\n  everyday sub-task still routes to the cheap tier. Trust `cognitum-auto`.\n- Use **`metallm_delegate`** for agentic sub-tasks needing tools/files in a working dir\n  (its `cwd` is sandboxed); use **`metallm_ask`** for a single-shot question — it returns\n  the gateway's real metered cost + resolved tier/model in-band.\n- Reserve the main (inline) session for orchestration, integration, and final review;\n  push expensive per-sub-task reasoning through the gateway.\n\n**Setup (per developer, local — never committed):** register the `metallm-dev-bridge` MCP\nserver via a local `.mcp.json` (gitignored) and export your gateway key as `COGNITUM_DEV_KEY`\nin your shell. Build steps + the exact `.mcp.json` block are in the internal meta-llm\ndev-bridge README. **Never commit the key or an inline gateway URL.**\n\n### `ask` vs `delegate` — pick by task shape (load-bearing)\n\n**Use `metallm_ask` for single-shot facts, summaries, classification, and small code\nquestions. Use `metallm_delegate` only when the task needs autonomous multi-step execution\nor isolated agent context.**\n\nWhy the split is strict: `metallm_delegate` spawns a full `claude -p` sub-agent, which loads\nits entire harness context **even for a trivial task** — measured floor ≈ **$0.26/call**\n(~43k input tokens) before any real work. `metallm_ask` is a single gateway completion —\nmeasured ≈ **$0.0001** for a small query, ~2500× cheaper. So delegating casually is\nexpensive at volume; `delegate` pays off only when offloading the sub-task's context from\nthe main session is worth the floor. When in doubt, `ask`.\n\nRouting caveat (tracked): `metallm_ask` **auto** currently over-tiers some trivial prompts to\n`mid` (sonnet-5) instead of `low` — the bridge's `/v1/messages` path may miss ADR-236\nhost-normalization (meta-llm issue #38). Forced tiers work correctly; cost impact is small\nper call but real at volume.\n","category":"root","tokens":16551},{"name":"AGENTS.md","path":"AGENTS.md","title":"AGENTS.md","content":"# Claude Flow V3 - Agent Guide\n\n> **For OpenAI Codex CLI** - Agentic AI Foundation standard\n> Skills: `$skill-name` | Config: `.agents/config.toml`\n\n---\n\n## 📢 TL;DR - READ THIS FIRST\n\n```\n╔═══════════════════════════════════════════════════════════════════════════╗\n║  1. claude-flow = LEDGER (tracks state, stores memory, coordinates)       ║\n║  2. Codex = EXECUTOR (writes code, runs commands, creates files)          ║\n║  3. NEVER stop after calling claude-flow - IMMEDIATELY continue working   ║\n║  4. If you need something BUILT/EXECUTED, YOU do it, not claude-flow      ║\n║  5. ALWAYS search memory BEFORE starting: memory search --query \"task\"    ║\n║  6. ALWAYS store patterns AFTER success: memory store --namespace patterns║\n╚═══════════════════════════════════════════════════════════════════════════╝\n```\n\n**Workflow (Use MCP Tools):**\n1. `memory_search(query=\"task keywords\")` → LEARN from past patterns (score > 0.7 = use it)\n2. `swarm_init(topology=\"hierarchical\")` → coordination record (instant)\n3. **YOU write the code / run the commands** ← THIS IS WHERE WORK HAPPENS\n4. `memory_store(key=\"pattern-x\", value=\"what worked\", namespace=\"patterns\")` → REMEMBER for next time\n\n---\n\n## Ruflo Policy-Governed Concurrent Codex Workflow\n\nRuflo is the coordination ledger and policy decision point. Codex agents are\nthe executors. Coordination records do not write code or run tests.\n\nUse `guidance_brain({ mode: \"recommend\", task: \"...\" })` to select Ruflo\ncapabilities from the live MCP registry. A registered tool is not necessarily\nconfigured, reachable, healthy, or authorized. If it is unavailable, continue\nwith compatible guidance tools, CLI discovery, and repository instructions.\n\n1. Recall relevant AgentDB memory and ADRs.\n2. Inspect source, runtime, dependencies, policy, and health.\n3. Route to the smallest capable topology, agents, skills, and tools.\n4. Plan acceptance criteria, safety envelope, ownership, and validation.\n5. Execute with Codex workers in isolated scopes; Ruflo records coordination.\n6. Test focused, regression, and failure paths.\n7. Validate types, security, policy, compatibility, and artifact integrity.\n8. Benchmark a source-bound candidate against a source-bound baseline.\n9. Optimize only measured bottlenecks without weakening safety.\n10. Bind claims and evidence into exact source/build receipts.\n11. Reconcile handoffs and disclose unresolved limitations.\n12. Publish only through a separately authorized release gate.\n\nHard invariants:\n\n- Never run two writers in one worktree.\n- Delegation may only reduce tools, servers, namespaces, network, spend,\n  concurrency, expiry, and depth.\n- Policy denial cancels dependent work before side effects.\n- MetaHarness may evaluate candidates concurrently, but only ADR-322A may\n  promote them and MetaHarness may never expand its own SafetyEnvelope.\n- Do not commit, push, merge, release, or remove worktrees unless authorized.\n- Existing installations migrate in `legacy` policy mode; use `observe` before\n  switching to `enforce`.\n\nRepository harness integration:\n\n- If tracked repository instructions define a collaboration harness, start its\n  session only after assigning an isolated worktree.\n- Inspect existing claims, acquire exact paths/resources/ports, renew leases,\n  check acknowledged inbox messages at integration boundaries, and release ownership on\n  handoff or exit.\n- A repository lease coordinates ownership; it does not grant authorization.\n  Protected work still requires the ADR-324/325 action capability and current\n  fencing epoch.\n- In-memory reference adapters demonstrate semantics; they are not distributed,\n  restart-durable release authorities.\n- Heartbeats and lease expiry establish liveness; a PID is diagnostic only.\n- `HEAD` alone is not an exact source-state identity in a dirty worktree.\n  Release evidence must bind a clean commit or an immutable snapshot of tracked\n  and untracked changes.\n\nUseful checks:\n\n```bash\nnpx ruflo policy status\nnpx ruflo policy verify\nnpx ruflo metaharness flywheel status\n```\n\nRepository release contract:\n\n- The stable public train is exactly `@claude-flow/cli`, `claude-flow`, and\n  `ruflo`; internal `@claude-flow/*` components are bundled and are not part of\n  a normal standalone publish.\n- Publish from a clean, reviewed source state in that order.\n- Only the CLI publish receives the helper-signing configuration from\n  `ruv-dev`; use the existing authenticated npm session for publication.\n- Run `node scripts/audit-umbrella-version-lockstep.mjs`, verify all three\n  registry versions, and align `latest`, `alpha`, and `v3alpha`.\n\n---\n\n## 🚨 CRITICAL: CODEX DOES THE WORK, CLAUDE-FLOW ORCHESTRATES\n\n```\n┌─────────────────────────────────────────────────────────────┐\n│  CLAUDE-FLOW = ORCHESTRATOR (tracks state, coordinates)     │\n│  CODEX = WORKER (writes code, runs commands, implements)    │\n└─────────────────────────────────────────────────────────────┘\n```\n\n### ❌ WRONG: Expecting claude-flow to execute tasks\n```bash\nnpx claude-flow swarm start --objective \"Build API\"\n# WRONG: Waiting for claude-flow to build the API\n# Claude-flow does NOT execute code!\n```\n\n### ✅ CORRECT: Codex executes, claude-flow tracks\n```bash\n# 1. Tell claude-flow what you're doing (optional coordination)\nnpx claude-flow swarm init --topology hierarchical --max-agents 1\nnpx claude-flow agent spawn --type coder --name codex-worker\n\n# 2. YOU (CODEX) DO THE ACTUAL WORK:\nmkdir -p src\ncat > src/api.ts << 'EOF'\nexport function hello() { return \"Hello World\"; }\nEOF\n\n# 3. Report to claude-flow what you did (optional)\nnpx claude-flow memory store --key \"api-created\" --value \"src/api.ts\" --namespace results\n```\n\n### The Division of Labor\n\n| Component | Role | Examples |\n|-----------|------|----------|\n| **CODEX** | EXECUTES | Write files, run tests, create code, shell commands |\n| **claude-flow** | ORCHESTRATES | Track agents, store memory, coordinate tasks |\n\n---\n\n## ⛔ DON'T STOP AFTER CALLING CLAUDE-FLOW\n\n```\n┌─────────────────────────────────────────────────────────────────────────┐\n│  ❌ WRONG: Call claude-flow → STOP → Wait for results                   │\n│  ✅ RIGHT: Call claude-flow → IMMEDIATELY continue → YOU do the work    │\n└─────────────────────────────────────────────────────────────────────────┘\n```\n\n### ❌ WRONG Pattern (Stopping)\n```bash\nnpx claude-flow swarm init --topology hierarchical\nnpx claude-flow agent spawn --type coder --name worker-1\nnpx claude-flow swarm start --objective \"Build hello world\"\n# WRONG: Codex stops here and waits for something to happen\n# Nothing will happen! Claude-flow doesn't execute code!\n```\n\n### ✅ CORRECT Pattern (Continue Immediately)\n```bash\n# Step 1: Coordination (optional)\nnpx claude-flow swarm init --topology hierarchical\nnpx claude-flow agent spawn --type coder --name worker-1\n\n# Step 2: IMMEDIATELY DO THE WORK YOURSELF - DON'T WAIT!\necho 'console.log(\"Hello World!\");' > hello.js\nnode hello.js\n\n# Step 3: Report what you did\nnpx claude-flow memory store --key \"result\" --value \"Hello World printed\" --namespace results\n```\n\n### The Rule\n**After ANY claude-flow command, IMMEDIATELY continue with your own work.**\n\nClaude-flow commands return instantly. They create coordination RECORDS only.\nYou must ALWAYS follow up with YOUR OWN execution.\n\n| After This... | IMMEDIATELY Do This... |\n|---------------|----------------------|\n| `swarm init` | Start writing code |\n| `agent spawn` | Continue implementation |\n| `task create` | Execute the task yourself |\n| `swarm start` | Begin actual work |\n\n---\n\n### When to Use Claude-Flow Commands\n\n| Use Case | Claude-Flow Command | Then Codex Does |\n|----------|---------------------|-----------------|\n| Track progress | `memory store --key \"step1\" --value \"done\"` | Continue to next step |\n| Multi-step tasks | `task create --description \"step 2\"` | Execute step 2 |\n| Store results | `memory store --key \"output\" --value \"...\"` | Move on |\n| Coordinate | `swarm init` | Start working |\n\n### Hello World - Correct Pattern\n\n```bash\n# STEP 1: Optional - register with orchestrator\nnpx claude-flow swarm init --topology mesh --max-agents 1\n\n# STEP 2: CODEX DOES THE WORK\necho 'console.log(\"Hello World!\");' > hello.js\nnode hello.js\n\n# STEP 3: Optional - report completion\nnpx claude-flow memory store --key \"hello-result\" --value \"printed Hello World\" --namespace results\n```\n\n**REMEMBER: If you need something DONE, YOU do it. Claude-flow just tracks.**\n\n---\n\n## ⚡ QUICK COMMANDS (NO DISCOVERY NEEDED)\n\n### Spawn N-Agent Swarm (Copy-Paste Ready)\n\n```bash\n# 5-AGENT SWARM - Run these commands in sequence:\nnpx claude-flow swarm init --topology hierarchical --max-agents 8\nnpx claude-flow agent spawn --type coordinator --name coord-1\nnpx claude-flow agent spawn --type coder --name coder-1\nnpx claude-flow agent spawn --type coder --name coder-2\nnpx claude-flow agent spawn --type tester --name tester-1\nnpx claude-flow agent spawn --type reviewer --name reviewer-1\nnpx claude-flow swarm start --objective \"Your task here\" --strategy development\n```\n\n### Common Swarm Patterns\n\n| Task | Exact Command |\n|------|---------------|\n| Init hierarchical swarm | `npx claude-flow swarm init --topology hierarchical --max-agents 8` |\n| Init mesh swarm | `npx claude-flow swarm init --topology mesh --max-agents 5` |\n| Init V3 mode (15 agents) | `npx claude-flow swarm init --v3-mode` |\n| Spawn coder | `npx claude-flow agent spawn --type coder --name coder-1` |\n| Spawn tester | `npx claude-flow agent spawn --type tester --name tester-1` |\n| Spawn coordinator | `npx claude-flow agent spawn --type coordinator --name coord-1` |\n| Spawn architect | `npx claude-flow agent spawn --type architect --name arch-1` |\n| Spawn reviewer | `npx claude-flow agent spawn --type reviewer --name rev-1` |\n| Spawn researcher | `npx claude-flow agent spawn --type researcher --name res-1` |\n| Start swarm | `npx claude-flow swarm start --objective \"task\" --strategy development` |\n| Check swarm status | `npx claude-flow swarm status` |\n| List agents | `npx claude-flow agent list` |\n| Stop swarm | `npx claude-flow swarm stop` |\n\n### Agent Types (Use with `--type`)\n\n| Type | Purpose |\n|------|---------|\n| `coordinator` | Orchestrates other agents |\n| `coder` | Writes code |\n| `tester` | Writes tests |\n| `reviewer` | Reviews code |\n| `architect` | Designs systems |\n| `researcher` | Analyzes requirements |\n| `security-architect` | Security design |\n| `performance-engineer` | Optimization |\n\n### Task Commands\n\n| Action | Command |\n|--------|---------|\n| Create task | `npx claude-flow task create --type implementation --description \"desc\"` |\n| List tasks | `npx claude-flow task list` |\n| Assign task | `npx claude-flow task assign TASK_ID --agent AGENT_NAME` |\n| Task status | `npx claude-flow task status TASK_ID` |\n| Cancel task | `npx claude-flow task cancel TASK_ID` |\n\n### Memory Commands\n\n| Action | Command |\n|--------|---------|\n| Store | `npx claude-flow memory store --key \"key\" --value \"value\" --namespace patterns` |\n| Search | `npx claude-flow memory search --query \"search terms\"` |\n| List | `npx claude-flow memory list --namespace patterns` |\n| Retrieve | `npx claude-flow memory retrieve --key \"key\"` |\n\n---\n\n## 🚀 SWARM RECIPES\n\n### Recipe 1: Hello World Test (COMPLETE EXAMPLE)\n\n**Step 1: Setup coordination** (returns instantly - don't stop!)\n```bash\nnpx claude-flow swarm init --topology mesh --max-agents 5\nnpx claude-flow agent spawn --type coder --name hello-main\n# ⚠️ DON'T STOP HERE - CONTINUE IMMEDIATELY TO STEP 2\n```\n\n**Step 2: YOU (Codex) execute the task** (THIS IS THE REAL WORK)\n```bash\n# ✅ YOU create the file\necho 'console.log(\"Hello World from Swarm!\");' > /tmp/hello-swarm.js\n\n# ✅ YOU execute it\nnode /tmp/hello-swarm.js\n# Output: Hello World from Swarm!\n```\n\n**Step 3: Report completion** (optional - store results)\n```bash\nnpx claude-flow memory store --key \"hello-world-result\" --value \"Executed: Hello World from Swarm!\" --namespace results\n```\n\n### Recipe 1b: 5-Agent Concurrent Hello World (COMPLETE)\n```bash\n# COORDINATION (instant - creates records only)\nnpx claude-flow swarm init --topology hierarchical --max-agents 5\nfor i in 1 2 3 4 5; do\n  npx claude-flow agent spawn --type coder --name \"worker-$i\"\ndone\n\n# ⚠️ NOW YOU DO THE ACTUAL CONCURRENT WORK:\nfor i in 1 2 3 4 5; do\n  (echo \"Worker $i: Hello World!\" && sleep 0.$i) &\ndone\nwait\necho \"All 5 workers completed!\"\n\n# REPORT (optional)\nnpx claude-flow memory store --key \"concurrent-result\" --value \"5 workers completed\" --namespace results\n```\n\n### Recipe 1b: Hello World (Single Command Block)\n```bash\n# All-in-one execution\nnpx claude-flow swarm init --topology mesh --max-agents 5 && \\\nnpx claude-flow agent spawn --type coder --name hello-main && \\\nnpx claude-flow swarm start --objective \"Print hello world\" --strategy development && \\\necho 'console.log(\"Hello World from Swarm!\");' > /tmp/hello-swarm.js && \\\nnode /tmp/hello-swarm.js && \\\nnpx claude-flow memory store --key \"hello-world-result\" --value \"Success\" --namespace results\n```\n\n### Recipe 2: Feature Implementation (6 Agents)\n```bash\nnpx claude-flow swarm init --topology hierarchical --max-agents 8\nnpx claude-flow agent spawn --type coordinator --name lead\nnpx claude-flow agent spawn --type architect --name arch\nnpx claude-flow agent spawn --type coder --name impl-1\nnpx claude-flow agent spawn --type coder --name impl-2\nnpx claude-flow agent spawn --type tester --name test\nnpx claude-flow agent spawn --type reviewer --name review\nnpx claude-flow swarm start --objective \"Implement [feature]\" --strategy development\n```\n\n### Recipe 3: Bug Fix (4 Agents)\n```bash\nnpx claude-flow swarm init --topology hierarchical --max-agents 4\nnpx claude-flow agent spawn --type coordinator --name lead\nnpx claude-flow agent spawn --type researcher --name debug\nnpx claude-flow agent spawn --type coder --name fix\nnpx claude-flow agent spawn --type tester --name verify\nnpx claude-flow swarm start --objective \"Fix [bug]\" --strategy development\n```\n\n### Recipe 4: Security Audit (3 Agents)\n```bash\nnpx claude-flow swarm init --topology hierarchical --max-agents 4\nnpx claude-flow agent spawn --type coordinator --name lead\nnpx claude-flow agent spawn --type security-architect --name audit\nnpx claude-flow agent spawn --type reviewer --name review\nnpx claude-flow swarm start --objective \"Security audit\" --strategy development\n```\n\n### Recipe 5: V3 Full Coordination (15 Agents)\n```bash\nnpx claude-flow swarm init --v3-mode\nnpx claude-flow swarm coordinate --agents 15\n```\n\n---\n\n## 📋 BEHAVIORAL RULES\n\n- **YOU (CODEX) execute tasks** - claude-flow only orchestrates\n- Do what is asked; nothing more, nothing less\n- NEVER create files unless absolutely necessary\n- ALWAYS prefer editing existing files\n- NEVER save to root folder\n- NEVER commit secrets or .env files\n- ALWAYS read a file before editing it\n- NEVER wait for claude-flow to \"do work\" - it doesn't execute, YOU do\n- Use claude-flow commands to TRACK progress, not to EXECUTE tasks\n\n## 📁 FILE ORGANIZATION\n\n| Directory | Purpose |\n|-----------|---------|\n| `/src` | Source code |\n| `/tests` | Test files |\n| `/docs` | Documentation |\n| `/config` | Configuration |\n| `/scripts` | Utility scripts |\n\n## 🎯 WHEN TO USE SWARMS\n\n**USE SWARM:**\n- Multiple files (3+)\n- New feature implementation\n- Cross-module refactoring\n- API changes with tests\n- Security-related changes\n- Performance optimization\n\n**SKIP SWARM:**\n- Single file edits\n- Simple bug fixes (1-2 lines)\n- Documentation updates\n- Configuration changes\n\n---\n\n## 🔧 CLI REFERENCE\n\n### Swarm Commands\n```bash\nnpx claude-flow swarm init [--topology TYPE] [--max-agents N] [--v3-mode]\nnpx claude-flow swarm start --objective \"task\" --strategy [development|research]\nnpx claude-flow swarm status [SWARM_ID]\nnpx claude-flow swarm stop [SWARM_ID]\nnpx claude-flow swarm scale --count N\nnpx claude-flow swarm coordinate --agents N\n```\n\n### Agent Commands\n```bash\nnpx claude-flow agent spawn --type TYPE --name NAME\nnpx claude-flow agent list [--filter active|idle|busy]\nnpx claude-flow agent status AGENT_ID\nnpx claude-flow agent stop AGENT_ID\nnpx claude-flow agent metrics [AGENT_ID]\nnpx claude-flow agent health\nnpx claude-flow agent logs AGENT_ID\n```\n\n### Task Commands\n```bash\nnpx claude-flow task create --type TYPE --description \"desc\"\nnpx claude-flow task list [--all]\nnpx claude-flow task status TASK_ID\nnpx claude-flow task assign TASK_ID --agent AGENT_NAME\nnpx claude-flow task cancel TASK_ID\nnpx claude-flow task retry TASK_ID\n```\n\n### Memory Commands\n```bash\nnpx claude-flow memory store --key KEY --value VALUE [--namespace NS]\nnpx claude-flow memory search --query \"terms\" [--namespace NS]\nnpx claude-flow memory list [--namespace NS]\nnpx claude-flow memory retrieve --key KEY [--namespace NS]\nnpx claude-flow memory init [--force]\n```\n\n### Hooks Commands\n```bash\nnpx claude-flow hooks pre-task --description \"task\"\nnpx claude-flow hooks post-task --task-id ID --success true\nnpx claude-flow hooks route --task \"task\"\nnpx claude-flow hooks session-start --session-id ID\nnpx claude-flow hooks session-end --export-metrics true\nnpx claude-flow hooks worker list\nnpx claude-flow hooks worker dispatch --trigger audit\n```\n\n### System Commands\n```bash\nnpx claude-flow init [--wizard] [--codex] [--full]\nnpx claude-flow daemon start\nnpx claude-flow daemon stop\nnpx claude-flow daemon status\nnpx claude-flow doctor [--fix]\nnpx claude-flow status\nnpx claude-flow mcp start\n```\n\n---\n\n## 🔌 TOPOLOGIES\n\n| Topology | Use Case | Command Flag |\n|----------|----------|--------------|\n| `hierarchical` | Coordinated teams, anti-drift | `--topology hierarchical` |\n| `mesh` | Peer-to-peer, equal agents | `--topology mesh` |\n| `hierarchical-mesh` | Hybrid (recommended for V3) | `--topology hierarchical-mesh` |\n| `ring` | Sequential processing | `--topology ring` |\n| `star` | Central coordinator | `--topology star` |\n| `adaptive` | Dynamic switching | `--topology adaptive` |\n\n## 🤖 AGENT TYPES\n\n### Core\n`coordinator`, `coder`, `tester`, `reviewer`, `architect`, `researcher`\n\n### Specialized\n`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`\n\n### Swarm Coordination\n`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`\n\n### Consensus\n`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`\n\n---\n\n## ⚙️ CONFIGURATION\n\n### Default Swarm Config\n- Topology: `hierarchical`\n- Max Agents: 8\n- Strategy: `specialized`\n- Consensus: `raft`\n- Memory: `hybrid`\n\n### Environment Variables\n```bash\nCLAUDE_FLOW_CONFIG=./claude-flow.config.json\nCLAUDE_FLOW_LOG_LEVEL=info\nCLAUDE_FLOW_MEMORY_BACKEND=hybrid\n```\n\n---\n\n## 🔗 SKILLS\n\nInvoke with `$skill-name`:\n\n| Skill | Purpose |\n|-------|---------|\n| `$swarm-orchestration` | Multi-agent coordination |\n| `$memory-management` | Pattern storage/retrieval |\n| `$sparc-methodology` | Structured development |\n| `$security-audit` | Security scanning |\n| `$performance-analysis` | Profiling |\n| `$github-automation` | CI/CD management |\n| `$hive-mind` | Byzantine consensus |\n| `$neural-training` | Pattern learning |\n\n---\n\n---\n\n## 🔌 MCP INTEGRATION (Learning & Coordination)\n\nCodex doesn't have native hooks like Claude Code, but uses **MCP (Model Context Protocol)** for learning and coordination.\n\n### MCP Auto-Registration\n\nWhen you run `npx claude-flow init --codex`, the MCP server is **automatically registered** with Codex.\n\n```bash\n# Verify MCP is registered:\ncodex mcp list\n\n# Expected output:\n# Name         Command  Args                   Status\n# claude-flow  npx      claude-flow mcp start  enabled\n\n# If not present, add manually:\ncodex mcp add claude-flow -- npx claude-flow mcp start\n```\n\n### Test MCP Connection\n```bash\n# Test MCP server starts correctly:\nnpx claude-flow mcp start --test\n```\n\n### MCP Tools Available\nOnce added, Codex can use these tools via MCP:\n\n**Coordination:**\n| Tool | Purpose |\n|------|---------|\n| `swarm_init` | Initialize swarm (topology, maxAgents) |\n| `swarm_status` | Check swarm state |\n| `agent_spawn` | Register agent roles |\n| `agent_status` | Check agent state |\n| `task_orchestrate` | Coordinate multi-agent tasks |\n\n**Learning & Memory (USE THESE!):**\n| Tool | Purpose | When |\n|------|---------|------|\n| `memory_search` | Semantic vector search | BEFORE every task |\n| `memory_store` | Store patterns with embeddings | AFTER success |\n| `memory_retrieve` | Get by exact key | When key is known |\n| `neural_train` | Train on patterns | Periodic improvement |\n| `neural_status` | Check learning state | Debugging |\n\n**Hive Mind (Advanced):**\n| Tool | Purpose |\n|------|---------|\n| `hive-mind_init` | Byzantine consensus swarm |\n| `hive-mind_spawn` | Spawn hive workers |\n| `hive-mind_broadcast` | Message all workers |\n\n### Self-Learning via MCP Tools (PREFERRED)\n\nUse MCP tools directly - faster than CLI commands:\n\n**BEFORE starting any task - SEARCH for patterns:**\n```\nUse tool: memory_search\n  query: \"keywords related to your task\"\n  namespace: \"patterns\"\n```\n\n**AFTER completing successfully - STORE the pattern:**\n```\nUse tool: memory_store\n  key: \"pattern-[descriptive-name]\"\n  value: \"What worked: approach, code patterns, gotchas\"\n  namespace: \"patterns\"\n```\n\n### MCP Learning Workflow (Use This!)\n\n```\n1. LEARN: memory_search(query=\"task keywords\", namespace=\"patterns\")\n   → If score > 0.7, USE that pattern\n\n2. COORDINATE: swarm_init(topology=\"hierarchical\")\n   → agent_spawn(type=\"coder\", name=\"worker-1\")\n\n3. EXECUTE: YOU write the code, run commands, create files\n\n4. REMEMBER: memory_store(key=\"pattern-x\", value=\"what worked\", namespace=\"patterns\")\n```\n\n### MCP Tools for Learning\n\n| Tool | Purpose | When to Use |\n|------|---------|-------------|\n| `memory_search` | Find similar past patterns | BEFORE starting any task |\n| `memory_store` | Save successful patterns | AFTER completing a task |\n| `memory_retrieve` | Get specific pattern by key | When you know the exact key |\n| `neural_train` | Train on successful patterns | After multiple successes |\n\n### Example: Learning-Enabled Task\n\n```\nSTEP 1 - LEARN:\nUse tool: memory_search\n  query: \"validation utility function\"\n  namespace: \"patterns\"\n\n→ Found: pattern-email-validator (score: 0.82)\n→ Use this pattern as reference!\n\nSTEP 2 - COORDINATE:\nUse tool: swarm_init with topology=\"hierarchical\", maxAgents=3\n\nSTEP 3 - EXECUTE:\nYOU create the files:\n  echo 'export function validate(x) { ... }' > /tmp/validator.js\n  node --test /tmp/validator.js\n\nSTEP 4 - REMEMBER:\nUse tool: memory_store\n  key: \"pattern-phone-validator\"\n  value: \"Phone validation: regex /^\\+?[\\d\\s-]{10,}$/, normalize first, test edge cases\"\n  namespace: \"patterns\"\n```\n\n### Vector Search Tips\n- Searches are SEMANTIC (meaning-based, not just keywords)\n- Score > 0.7 = strong match, use that pattern\n- Score 0.5-0.7 = partial match, adapt as needed\n- Store DETAILED values for better future retrieval\n\n### CLI Fallback (if MCP unavailable)\n```bash\nnpx claude-flow memory search --query \"keywords\" --namespace patterns\nnpx claude-flow memory store --key \"pattern-x\" --value \"what worked\" --namespace patterns\n```\n\n### Coordination via MCP\n\nWhen claude-flow is added as MCP server, Codex can call tools directly:\n```\nUse tool: swarm_init with topology=\"hierarchical\"\nUse tool: memory_store with key=\"result\" value=\"success\"\n```\n\n### config.toml MCP Setup\n```toml\n# ~/.codex/config.toml\n[mcp_servers.claude-flow]\ncommand = \"npx\"\nargs = [\"claude-flow\", \"mcp\", \"start\"]\nenabled = true\n```\n\n---\n\n## 📚 SUPPORT\n\n- Docs: https://github.com/ruvnet/claude-flow\n- Issues: https://github.com/ruvnet/claude-flow/issues\n\n**Remember: Codex executes, claude-flow orchestrates!**\n","category":"root","tokens":5897}]}