{"owner":"ruvnet","repo":"ruflo","hasSkills":true,"totalSkillsCount":5,"totalTokensCount":19896,"categories":["claude-rule","root-instruction","mcp-config","marketplace","plugin-manifest"],"hasMcp":true,"mcpConfig":{"mcpServers":{"ruflo":{"command":"npx","args":["-y","@modelcontextprotocol/server-ruflo"]}}},"found":["CLAUDE.md","AGENTS.md",".cursor/mcp.json",".claude-plugin/marketplace.json",".claude-plugin/plugin.json"],"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- **The internal `@claude-flow/*` leaves follow the same policy since 2026-09-28**\n  (moved to `3.0.0`; `cli-core` `3.7.0`; the two plugins `1.0.0`). One exception:\n  `@claude-flow/embeddings` stays on its alpha line — its registry `latest`\n  (`3.0.0-alpha.45`) was built from a branch not on `main`, and publishing from\n  `main` would drop 139 exported names. Reconcile that branch before bumping it.\n\n### Publishing Rules\n\n- The normal public release train is exactly THREE packages:\n  `@claude-flow/cli`, `claude-flow`, and `ruflo`.\n- **Exactly FOUR `@claude-flow/*` components are bundled** into the public\n  artifacts: `security`, `codex`, `mcp`, `plugin-agent-federation` — the list\n  is `INTERNAL_RUNTIME_PACKAGES` in `scripts/stage-internal-runtime-bundles.mjs`.\n  These are built from the tagged source and staged into the tarball's\n  `package/node_modules/`, so a source change in them ships with the train.\n  They are ALSO published standalone for direct consumers (the staging script\n  copies only `dist` + `README.md`, independent of the standalone tarball) — when\n  their source changes, republish the standalone package too, or direct\n  consumers keep the old copy (the #3411 `mcp` disclosure was about the\n  standalone tarball, not the train).\n- Every publishable leaf needs a `files` allowlist and must NOT set\n  `publishConfig.tag`. Without `files`, npm ships whatever sits in the package\n  directory — published tarballs have leaked `.claude-flow/` daemon logs and\n  pids, `settings.json`, `.swarm/memory.db` and headless-worker prompt logs.\n  A `publishConfig.tag` of `v3alpha` silently routes a stable publish away\n  from `latest`.\n- **Every OTHER `@claude-flow/*` dependency resolves from the registry**, at the\n  version `v3/@claude-flow/cli/package.json` pins. A source change in one of\n  those does NOT ship with the train — the release silently carries the last\n  *published* copy of that package, not the code you just merged. It must be\n  bumped and published standalone in the same release or the fix reaches nobody:\n\n  | dep of `@claude-flow/cli` | bundled? | how a source change reaches users |\n  |---|---|---|\n  | `security`, `codex`, `mcp`, `plugin-agent-federation` | yes | with the train |\n  | `cli-core`, `neural`, `shared`, `memory` | **no** | **standalone publish required** |\n\n  `memory` is the easiest of these to miss: its own package tests run against\n  workspace source, so CI goes green on a change that cannot ship. Since #3414\n  the CLI pins every non-bundled leaf exactly, so a stale cached copy can no\n  longer satisfy the spec silently — but the pin now fails the other way: an\n  exact pin to a version that was never published breaks installs outright\n  (`memory@3.0.0-alpha.27` sat unpublished behind a merged pin on 2026-09-28).\n  `v3/.npmrc` sets `prefer-workspace-packages=true`, so `v3/pnpm-lock.yaml`\n  links every `@claude-flow/*` package to workspace source (without it, pnpm\n  swaps in a newer registry copy — e.g. a `cli` released from a branch not on\n  `main` — and drags that copy's alpha deps into the lockfile). The lockfile\n  therefore never proves a leaf was published: check `npm view <leaf>@<ver>`\n  before merging a pin. #3390 (#3327 Finding A) is the\n  worked example — it fixed `memory/src/controller-registry.ts` and\n  `cli/src/memory/memory-bridge.ts` together, and without a standalone `memory`\n  publish only the `cli` half would have shipped, leaving the fix inert.\n- Before tagging, check every non-bundled leaf for drift between what the CLI\n  pins and what the workspace source says — a mismatch means an unpublished\n  change is about to be skipped by the release:\n\n  ```bash\n  # needs root deps for `semver` — run after `npm ci` at repo root\n  node -e 'const semver=require(\"semver\"),c=require(\"./v3/@claude-flow/cli/package.json\"),d={...c.dependencies,...c.optionalDependencies},b=[\"security\",\"codex\",\"mcp\",\"plugin-agent-federation\"];let n_=0;for(const[n,v]of Object.entries(d)){if(!n.startsWith(\"@claude-flow/\"))continue;if(b.includes(n.slice(13)))continue;let w;try{w=require(`./v3/${n}/package.json`).version}catch{continue}n_++;if(!semver.satisfies(w,v,{includePrerelease:true}))console.log(`DRIFT ${n}: cli pins ${v}, workspace source ${w} — publish it or the release skips the change`)}if(!n_){console.error(\"checked 0 leaves — check is broken, do not trust a clean result\");process.exit(1)}console.log(`checked ${n_} non-bundled leaves`)'\n  ```\n\n  It must use `semver.satisfies`, not a string compare: a pin may be a range,\n  and a literal match would then report a false DRIFT. It also fails loudly\n  at zero leaves checked — a guard that inspects nothing must not report clean.\n- **The drift check above only proves the CLI's pin and the workspace version agree with\n  EACH OTHER — it says nothing about whether that version is actually on npm.** #4303\n  (2026-10-20) shipped `@claude-flow/cli@3.57.2` depending on `@claude-flow/memory@3.0.6`,\n  which had never been published — #4279 bumped the workspace version and the CLI's pin\n  together, so the drift check above was clean, but nobody ran the standalone `npm\n  publish` for `memory`. Every fresh install of that line failed with `ETARGET`. Run\n  `node scripts/audit-leaf-versions-published.mjs` before tagging — it queries the live\n  npm registry for every non-bundled leaf pin and fails if the version it resolves to was\n  never published. This is now also a required CI check (`plugin-package-audit` job in\n  `v3-ci.yml`), so a PR that bumps a pin ahead of its own leaf's publish fails on the PR,\n  not on a consumer's install.\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","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",".cursor/mcp.json":"# Model Context Protocol (MCP) Configuration\n\nPath: `.cursor/mcp.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.cursor/mcp.json)",".claude-plugin/marketplace.json":"# Claude Plugin Marketplace Catalog\n\nPath: `.claude-plugin/marketplace.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.claude-plugin/marketplace.json)",".claude-plugin/plugin.json":"# claude-plugin Plugin Manifest\n\nPath: `.claude-plugin/plugin.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.claude-plugin/plugin.json)"},"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- **The internal `@claude-flow/*` leaves follow the same policy since 2026-09-28**\n  (moved to `3.0.0`; `cli-core` `3.7.0`; the two plugins `1.0.0`). One exception:\n  `@claude-flow/embeddings` stays on its alpha line — its registry `latest`\n  (`3.0.0-alpha.45`) was built from a branch not on `main`, and publishing from\n  `main` would drop 139 exported names. Reconcile that branch before bumping it.\n\n### Publishing Rules\n\n- The normal public release train is exactly THREE packages:\n  `@claude-flow/cli`, `claude-flow`, and `ruflo`.\n- **Exactly FOUR `@claude-flow/*` components are bundled** into the public\n  artifacts: `security`, `codex`, `mcp`, `plugin-agent-federation` — the list\n  is `INTERNAL_RUNTIME_PACKAGES` in `scripts/stage-internal-runtime-bundles.mjs`.\n  These are built from the tagged source and staged into the tarball's\n  `package/node_modules/`, so a source change in them ships with the train.\n  They are ALSO published standalone for direct consumers (the staging script\n  copies only `dist` + `README.md`, independent of the standalone tarball) — when\n  their source changes, republish the standalone package too, or direct\n  consumers keep the old copy (the #3411 `mcp` disclosure was about the\n  standalone tarball, not the train).\n- Every publishable leaf needs a `files` allowlist and must NOT set\n  `publishConfig.tag`. Without `files`, npm ships whatever sits in the package\n  directory — published tarballs have leaked `.claude-flow/` daemon logs and\n  pids, `settings.json`, `.swarm/memory.db` and headless-worker prompt logs.\n  A `publishConfig.tag` of `v3alpha` silently routes a stable publish away\n  from `latest`.\n- **Every OTHER `@claude-flow/*` dependency resolves from the registry**, at the\n  version `v3/@claude-flow/cli/package.json` pins. A source change in one of\n  those does NOT ship with the train — the release silently carries the last\n  *published* copy of that package, not the code you just merged. It must be\n  bumped and published standalone in the same release or the fix reaches nobody:\n\n  | dep of `@claude-flow/cli` | bundled? | how a source change reaches users |\n  |---|---|---|\n  | `security`, `codex`, `mcp`, `plugin-agent-federation` | yes | with the train |\n  | `cli-core`, `neural`, `shared`, `memory` | **no** | **standalone publish required** |\n\n  `memory` is the easiest of these to miss: its own package tests run against\n  workspace source, so CI goes green on a change that cannot ship. Since #3414\n  the CLI pins every non-bundled leaf exactly, so a stale cached copy can no\n  longer satisfy the spec silently — but the pin now fails the other way: an\n  exact pin to a version that was never published breaks installs outright\n  (`memory@3.0.0-alpha.27` sat unpublished behind a merged pin on 2026-09-28).\n  `v3/.npmrc` sets `prefer-workspace-packages=true`, so `v3/pnpm-lock.yaml`\n  links every `@claude-flow/*` package to workspace source (without it, pnpm\n  swaps in a newer registry copy — e.g. a `cli` released from a branch not on\n  `main` — and drags that copy's alpha deps into the lockfile). The lockfile\n  therefore never proves a leaf was published: check `npm view <leaf>@<ver>`\n  before merging a pin. #3390 (#3327 Finding A) is the\n  worked example — it fixed `memory/src/controller-registry.ts` and\n  `cli/src/memory/memory-bridge.ts` together, and without a standalone `memory`\n  publish only the `cli` half would have shipped, leaving the fix inert.\n- Before tagging, check every non-bundled leaf for drift between what the CLI\n  pins and what the workspace source says — a mismatch means an unpublished\n  change is about to be skipped by the release:\n\n  ```bash\n  # needs root deps for `semver` — run after `npm ci` at repo root\n  node -e 'const semver=require(\"semver\"),c=require(\"./v3/@claude-flow/cli/package.json\"),d={...c.dependencies,...c.optionalDependencies},b=[\"security\",\"codex\",\"mcp\",\"plugin-agent-federation\"];let n_=0;for(const[n,v]of Object.entries(d)){if(!n.startsWith(\"@claude-flow/\"))continue;if(b.includes(n.slice(13)))continue;let w;try{w=require(`./v3/${n}/package.json`).version}catch{continue}n_++;if(!semver.satisfies(w,v,{includePrerelease:true}))console.log(`DRIFT ${n}: cli pins ${v}, workspace source ${w} — publish it or the release skips the change`)}if(!n_){console.error(\"checked 0 leaves — check is broken, do not trust a clean result\");process.exit(1)}console.log(`checked ${n_} non-bundled leaves`)'\n  ```\n\n  It must use `semver.satisfies`, not a string compare: a pin may be a range,\n  and a literal match would then report a false DRIFT. It also fails loudly\n  at zero leaves checked — a guard that inspects nothing must not report clean.\n- **The drift check above only proves the CLI's pin and the workspace version agree with\n  EACH OTHER — it says nothing about whether that version is actually on npm.** #4303\n  (2026-10-20) shipped `@claude-flow/cli@3.57.2` depending on `@claude-flow/memory@3.0.6`,\n  which had never been published — #4279 bumped the workspace version and the CLI's pin\n  together, so the drift check above was clean, but nobody ran the standalone `npm\n  publish` for `memory`. Every fresh install of that line failed with `ETARGET`. Run\n  `node scripts/audit-leaf-versions-published.mjs` before tagging — it queries the live\n  npm registry for every non-bundled leaf pin and fails if the version it resolves to was\n  never published. This is now also a required CI check (`plugin-package-audit` job in\n  `v3-ci.yml`), so a PR that bumps a pin ahead of its own leaf's publish fails on the PR,\n  not on a consumer's install.\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","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",".cursor/mcp.json":"# Model Context Protocol (MCP) Configuration\n\nPath: `.cursor/mcp.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.cursor/mcp.json)",".claude-plugin/marketplace.json":"# Claude Plugin Marketplace Catalog\n\nPath: `.claude-plugin/marketplace.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.claude-plugin/marketplace.json)",".claude-plugin/plugin.json":"# claude-plugin Plugin Manifest\n\nPath: `.claude-plugin/plugin.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.claude-plugin/plugin.json)"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","rawUrl":"https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/AGENTS.md","title":"AI Agent Protocol & Instructions","category":"root-instruction","format":"markdown","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","isInternal":false,"tokens":6176,"sizeBytes":24566},{"name":"CLAUDE.md","path":"CLAUDE.md","rawUrl":"https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/CLAUDE.md","title":"Claude Agent Guidelines & System Prompt","category":"claude-rule","format":"markdown","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- **The internal `@claude-flow/*` leaves follow the same policy since 2026-09-28**\n  (moved to `3.0.0`; `cli-core` `3.7.0`; the two plugins `1.0.0`). One exception:\n  `@claude-flow/embeddings` stays on its alpha line — its registry `latest`\n  (`3.0.0-alpha.45`) was built from a branch not on `main`, and publishing from\n  `main` would drop 139 exported names. Reconcile that branch before bumping it.\n\n### Publishing Rules\n\n- The normal public release train is exactly THREE packages:\n  `@claude-flow/cli`, `claude-flow`, and `ruflo`.\n- **Exactly FOUR `@claude-flow/*` components are bundled** into the public\n  artifacts: `security`, `codex`, `mcp`, `plugin-agent-federation` — the list\n  is `INTERNAL_RUNTIME_PACKAGES` in `scripts/stage-internal-runtime-bundles.mjs`.\n  These are built from the tagged source and staged into the tarball's\n  `package/node_modules/`, so a source change in them ships with the train.\n  They are ALSO published standalone for direct consumers (the staging script\n  copies only `dist` + `README.md`, independent of the standalone tarball) — when\n  their source changes, republish the standalone package too, or direct\n  consumers keep the old copy (the #3411 `mcp` disclosure was about the\n  standalone tarball, not the train).\n- Every publishable leaf needs a `files` allowlist and must NOT set\n  `publishConfig.tag`. Without `files`, npm ships whatever sits in the package\n  directory — published tarballs have leaked `.claude-flow/` daemon logs and\n  pids, `settings.json`, `.swarm/memory.db` and headless-worker prompt logs.\n  A `publishConfig.tag` of `v3alpha` silently routes a stable publish away\n  from `latest`.\n- **Every OTHER `@claude-flow/*` dependency resolves from the registry**, at the\n  version `v3/@claude-flow/cli/package.json` pins. A source change in one of\n  those does NOT ship with the train — the release silently carries the last\n  *published* copy of that package, not the code you just merged. It must be\n  bumped and published standalone in the same release or the fix reaches nobody:\n\n  | dep of `@claude-flow/cli` | bundled? | how a source change reaches users |\n  |---|---|---|\n  | `security`, `codex`, `mcp`, `plugin-agent-federation` | yes | with the train |\n  | `cli-core`, `neural`, `shared`, `memory` | **no** | **standalone publish required** |\n\n  `memory` is the easiest of these to miss: its own package tests run against\n  workspace source, so CI goes green on a change that cannot ship. Since #3414\n  the CLI pins every non-bundled leaf exactly, so a stale cached copy can no\n  longer satisfy the spec silently — but the pin now fails the other way: an\n  exact pin to a version that was never published breaks installs outright\n  (`memory@3.0.0-alpha.27` sat unpublished behind a merged pin on 2026-09-28).\n  `v3/.npmrc` sets `prefer-workspace-packages=true`, so `v3/pnpm-lock.yaml`\n  links every `@claude-flow/*` package to workspace source (without it, pnpm\n  swaps in a newer registry copy — e.g. a `cli` released from a branch not on\n  `main` — and drags that copy's alpha deps into the lockfile). The lockfile\n  therefore never proves a leaf was published: check `npm view <leaf>@<ver>`\n  before merging a pin. #3390 (#3327 Finding A) is the\n  worked example — it fixed `memory/src/controller-registry.ts` and\n  `cli/src/memory/memory-bridge.ts` together, and without a standalone `memory`\n  publish only the `cli` half would have shipped, leaving the fix inert.\n- Before tagging, check every non-bundled leaf for drift between what the CLI\n  pins and what the workspace source says — a mismatch means an unpublished\n  change is about to be skipped by the release:\n\n  ```bash\n  # needs root deps for `semver` — run after `npm ci` at repo root\n  node -e 'const semver=require(\"semver\"),c=require(\"./v3/@claude-flow/cli/package.json\"),d={...c.dependencies,...c.optionalDependencies},b=[\"security\",\"codex\",\"mcp\",\"plugin-agent-federation\"];let n_=0;for(const[n,v]of Object.entries(d)){if(!n.startsWith(\"@claude-flow/\"))continue;if(b.includes(n.slice(13)))continue;let w;try{w=require(`./v3/${n}/package.json`).version}catch{continue}n_++;if(!semver.satisfies(w,v,{includePrerelease:true}))console.log(`DRIFT ${n}: cli pins ${v}, workspace source ${w} — publish it or the release skips the change`)}if(!n_){console.error(\"checked 0 leaves — check is broken, do not trust a clean result\");process.exit(1)}console.log(`checked ${n_} non-bundled leaves`)'\n  ```\n\n  It must use `semver.satisfies`, not a string compare: a pin may be a range,\n  and a literal match would then report a false DRIFT. It also fails loudly\n  at zero leaves checked — a guard that inspects nothing must not report clean.\n- **The drift check above only proves the CLI's pin and the workspace version agree with\n  EACH OTHER — it says nothing about whether that version is actually on npm.** #4303\n  (2026-10-20) shipped `@claude-flow/cli@3.57.2` depending on `@claude-flow/memory@3.0.6`,\n  which had never been published — #4279 bumped the workspace version and the CLI's pin\n  together, so the drift check above was clean, but nobody ran the standalone `npm\n  publish` for `memory`. Every fresh install of that line failed with `ETARGET`. Run\n  `node scripts/audit-leaf-versions-published.mjs` before tagging — it queries the live\n  npm registry for every non-bundled leaf pin and fails if the version it resolves to was\n  never published. This is now also a required CI check (`plugin-package-audit` job in\n  `v3-ci.yml`), so a PR that bumps a pin ahead of its own leaf's publish fails on the PR,\n  not on a consumer's install.\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","isInternal":false,"tokens":12820,"sizeBytes":50471},{"name":"marketplace.json","path":".claude-plugin/marketplace.json","rawUrl":"https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.claude-plugin/marketplace.json","title":"Claude Plugin Marketplace Catalog","category":"marketplace","format":"json","content":"# Claude Plugin Marketplace Catalog\n\nPath: `.claude-plugin/marketplace.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.claude-plugin/marketplace.json)","tokens":300,"sizeBytes":191},{"name":"plugin.json","path":".claude-plugin/plugin.json","rawUrl":"https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.claude-plugin/plugin.json","title":"claude-plugin Plugin Manifest","category":"plugin-manifest","format":"json","content":"# claude-plugin Plugin Manifest\n\nPath: `.claude-plugin/plugin.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.claude-plugin/plugin.json)","tokens":300,"sizeBytes":177},{"name":"mcp.json","path":".cursor/mcp.json","rawUrl":"https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.cursor/mcp.json","title":"Model Context Protocol (MCP) Configuration","category":"mcp-config","format":"json","content":"# Model Context Protocol (MCP) Configuration\n\nPath: `.cursor/mcp.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.cursor/mcp.json)","tokens":300,"sizeBytes":170}],"systemPromptSnippet":"<yakaai_skills repo=\"ruvnet/ruflo\">\n<!-- File: AGENTS.md (Tokens: ~6176 | Category: root-instruction) -->\n# 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\n<!-- File: CLAUDE.md (Tokens: ~12820 | Category: claude-rule) -->\n# 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- **The internal `@claude-flow/*` leaves follow the same policy since 2026-09-28**\n  (moved to `3.0.0`; `cli-core` `3.7.0`; the two plugins `1.0.0`). One exception:\n  `@claude-flow/embeddings` stays on its alpha line — its registry `latest`\n  (`3.0.0-alpha.45`) was built from a branch not on `main`, and publishing from\n  `main` would drop 139 exported names. Reconcile that branch before bumping it.\n\n### Publishing Rules\n\n- The normal public release train is exactly THREE packages:\n  `@claude-flow/cli`, `claude-flow`, and `ruflo`.\n- **Exactly FOUR `@claude-flow/*` components are bundled** into the public\n  artifacts: `security`, `codex`, `mcp`, `plugin-agent-federation` — the list\n  is `INTERNAL_RUNTIME_PACKAGES` in `scripts/stage-internal-runtime-bundles.mjs`.\n  These are built from the tagged source and staged into the tarball's\n  `package/node_modules/`, so a source change in them ships with the train.\n  They are ALSO published standalone for direct consumers (the staging script\n  copies only `dist` + `README.md`, independent of the standalone tarball) — when\n  their source changes, republish the standalone package too, or direct\n  consumers keep the old copy (the #3411 `mcp` disclosure was about the\n  standalone tarball, not the train).\n- Every publishable leaf needs a `files` allowlist and must NOT set\n  `publishConfig.tag`. Without `files`, npm ships whatever sits in the package\n  directory — published tarballs have leaked `.claude-flow/` daemon logs and\n  pids, `settings.json`, `.swarm/memory.db` and headless-worker prompt logs.\n  A `publishConfig.tag` of `v3alpha` silently routes a stable publish away\n  from `latest`.\n- **Every OTHER `@claude-flow/*` dependency resolves from the registry**, at the\n  version `v3/@claude-flow/cli/package.json` pins. A source change in one of\n  those does NOT ship with the train — the release silently carries the last\n  *published* copy of that package, not the code you just merged. It must be\n  bumped and published standalone in the same release or the fix reaches nobody:\n\n  | dep of `@claude-flow/cli` | bundled? | how a source change reaches users |\n  |---|---|---|\n  | `security`, `codex`, `mcp`, `plugin-agent-federation` | yes | with the train |\n  | `cli-core`, `neural`, `shared`, `memory` | **no** | **standalone publish required** |\n\n  `memory` is the easiest of these to miss: its own package tests run against\n  workspace source, so CI goes green on a change that cannot ship. Since #3414\n  the CLI pins every non-bundled leaf exactly, so a stale cached copy can no\n  longer satisfy the spec silently — but the pin now fails the other way: an\n  exact pin to a version that was never published breaks installs outright\n  (`memory@3.0.0-alpha.27` sat unpublished behind a merged pin on 2026-09-28).\n  `v3/.npmrc` sets `prefer-workspace-packages=true`, so `v3/pnpm-lock.yaml`\n  links every `@claude-flow/*` package to workspace source (without it, pnpm\n  swaps in a newer registry copy — e.g. a `cli` released from a branch not on\n  `main` — and drags that copy's alpha deps into the lockfile). The lockfile\n  therefore never proves a leaf was published: check `npm view <leaf>@<ver>`\n  before merging a pin. #3390 (#3327 Finding A) is the\n  worked example — it fixed `memory/src/controller-registry.ts` and\n  `cli/src/memory/memory-bridge.ts` together, and without a standalone `memory`\n  publish only the `cli` half would have shipped, leaving the fix inert.\n- Before tagging, check every non-bundled leaf for drift between what the CLI\n  pins and what the workspace source says — a mismatch means an unpublished\n  change is about to be skipped by the release:\n\n  ```bash\n  # needs root deps for `semver` — run after `npm ci` at repo root\n  node -e 'const semver=require(\"semver\"),c=require(\"./v3/@claude-flow/cli/package.json\"),d={...c.dependencies,...c.optionalDependencies},b=[\"security\",\"codex\",\"mcp\",\"plugin-agent-federation\"];let n_=0;for(const[n,v]of Object.entries(d)){if(!n.startsWith(\"@claude-flow/\"))continue;if(b.includes(n.slice(13)))continue;let w;try{w=require(`./v3/${n}/package.json`).version}catch{continue}n_++;if(!semver.satisfies(w,v,{includePrerelease:true}))console.log(`DRIFT ${n}: cli pins ${v}, workspace source ${w} — publish it or the release skips the change`)}if(!n_){console.error(\"checked 0 leaves — check is broken, do not trust a clean result\");process.exit(1)}console.log(`checked ${n_} non-bundled leaves`)'\n  ```\n\n  It must use `semver.satisfies`, not a string compare: a pin may be a range,\n  and a literal match would then report a false DRIFT. It also fails loudly\n  at zero leaves checked — a guard that inspects nothing must not report clean.\n- **The drift check above only proves the CLI's pin and the workspace version agree with\n  EACH OTHER — it says nothing about whether that version is actually on npm.** #4303\n  (2026-10-20) shipped `@claude-flow/cli@3.57.2` depending on `@claude-flow/memory@3.0.6`,\n  which had never been published — #4279 bumped the workspace version and the CLI's pin\n  together, so the drift check above was clean, but nobody ran the standalone `npm\n  publish` for `memory`. Every fresh install of that line failed with `ETARGET`. Run\n  `node scripts/audit-leaf-versions-published.mjs` before tagging — it queries the live\n  npm registry for every non-bundled leaf pin and fails if the version it resolves to was\n  never published. This is now also a required CI check (`plugin-package-audit` job in\n  `v3-ci.yml`), so a PR that bumps a pin ahead of its own leaf's publish fails on the PR,\n  not on a consumer's install.\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\n\n<!-- File: .claude-plugin/marketplace.json (Tokens: ~300 | Category: marketplace) -->\n# Claude Plugin Marketplace Catalog\n\nPath: `.claude-plugin/marketplace.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.claude-plugin/marketplace.json)\n\n<!-- File: .claude-plugin/plugin.json (Tokens: ~300 | Category: plugin-manifest) -->\n# claude-plugin Plugin Manifest\n\nPath: `.claude-plugin/plugin.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.claude-plugin/plugin.json)\n\n<!-- File: .cursor/mcp.json (Tokens: ~300 | Category: mcp-config) -->\n# Model Context Protocol (MCP) Configuration\n\nPath: `.cursor/mcp.json`\n\n[View Raw Content on GitHub](https://raw.githubusercontent.com/ruvnet/ruflo/HEAD/.cursor/mcp.json)\n</yakaai_skills>"}