| Dimension | Shared | Only in A | Only in B | Overlap |
|---|---|---|---|---|
| Sections | 0 | 16 | 60 | 0% |
| Commands | 1 | 9 | 39 | 2% |
| Section tags | 7 | 3 | 5 | 47% |
What each file covers
Sections
0 shared · 16 only in A · 60 only in B- − CLAUDE.md
- − Overview
- − Commands
- − Running a Single Test
- − Test Environments
- − Architecture
- − Stack
- − Key Directories
- − Text Generation Flow
- − Model Context Protocol (MCP)
- − LLM Router (Omni)
- − Database Collections
- − Environment Setup
- − MONGODB_URL is optional; omit for in-memory DB persisted to ./db
- − Code Conventions
- − Feature Development Checklist
- + Claude Code Configuration - Ruflo V3
- + Behavioral Rules (Always Enforced)
- + Capability Brain and Governed Implementation
- + File Organization
- + Project Architecture
- + Key Packages
- + Concurrent Automated Development
- + Swarm Orchestration
- + MCP + Task Tool in SAME Message
- + 3-Tier Model Routing (ADR-026, ADR-143)
- + Swarm Configuration & Anti-Drift
- + Anti-Drift Coding Swarm (PREFERRED DEFAULT)
- + Dual-Mode Collaboration (Claude Code + Codex)
- + Why Dual-Mode?
- + Dual-Mode Swarm Protocol
- + Collaboration Templates (Pre-Built Pipelines)
- + Dual-Mode CLI Commands
- + Run a collaboration template
- + Custom multi-platform swarm
- + Check collaboration status
- + List available templates
- + Shared Memory Coordination
- + Store context for cross-platform sharing
- + Search for patterns across all workers
- + Retrieve specific findings
- + Cross-Platform Learning
- + After successful collaboration, train patterns
- + Store successful collaboration patterns
- + Transfer learnings to both platforms
- + Worker Dependency Levels
- + Platform Strengths
- + Programmatic API
- + Swarm Protocols & Routing
- + Auto-Start Swarm Protocol
- + Agent Routing (Anti-Drift)
- + Task Complexity Detection
- + Project Configuration
- + V3 CLI Commands (26 Commands, 140+ Subcommands)
- + Core Commands
- + Advanced Commands
- + Quick CLI Examples
- + Initialize project
- + Start daemon with background workers
- + Spawn an agent
- + Initialize swarm
- + Search memory (HNSW-indexed)
- + System diagnostics
- + Security scan
- + Performance benchmark
- + Headless Background Instances (claude -p)
- + Basic Usage
- + Single headless task
- + With model selection
- + With output format
- + With budget limits
- + With specific tools allowed
- + Skip permissions (sandboxed environments only)
- + Parallel Background Execution
- + Spawn multiple headless instances in parallel
- + With results captured
Commands
1 shared · 9 only in A · 39 only in B- − npm run dev
- − npm run preview
- − npm run check
- − npm run lint
- − npm run format
- − npm run test
- − npx vitest run path/to/file.spec.ts
- − npx vitest run -t "test name"
- − npx vitest --watch path/to/file.spec.ts
- + npx claude-flow-codex dual run feature --task "Add user authentication with OAuth"
- + npx claude-flow-codex dual run security --target "./src"
- + npx claude-flow-codex dual run refactor --target "./src/legacy"
- + npx claude-flow-codex dual run \
- + npx claude-flow-codex dual status
- + npx claude-flow-codex dual templates
- + npx claude-flow@v3alpha memory store --namespace collaboration --key "design-decisions" --value "..."
- + npx claude-flow@v3alpha memory search --namespace collaboration --query "authentication patterns"
- + npx claude-flow@v3alpha memory retrieve --namespace collaboration --key "security-findings"
- + npx claude-flow@v3alpha hooks post-task --task-id "dual-[id]" --success true --train-neural true
- + npx claude-flow@v3alpha memory store --namespace patterns --key "dual-mode-[pattern]" --value "[what worked]"
- + npx claude-flow@v3alpha hooks transfer store --pattern "dual-collab-success"
- + npx claude-flow@v3alpha init --wizard
- + npx claude-flow@v3alpha daemon start
- + npx claude-flow@v3alpha agent spawn -t coder --name my-coder
- + npx claude-flow@v3alpha swarm init --v3-mode
- + npx claude-flow@v3alpha memory search -q "authentication patterns"
- + npx claude-flow@v3alpha doctor --fix
- + npx claude-flow@v3alpha security scan --depth full
- + npx claude-flow@v3alpha performance benchmark --suite all
- + npx claude-flow@v3alpha hooks teammate-idle --auto-assign true
- + npx claude-flow@v3alpha hooks task-completed -i task-123 --train-patterns true
- + npx claude-flow@v3alpha hooks pre-task --description "[task]"
- + npx claude-flow@v3alpha hooks post-task --task-id "[id]" --success true
- + npx claude-flow@v3alpha hooks post-edit --file "[file]" --train-patterns
- + npx claude-flow@v3alpha hooks session-start --session-id "[id]"
- + npx claude-flow@v3alpha hooks session-end --export-metrics true
- + npx claude-flow@v3alpha hooks session-restore --session-id "[id]"
- + npx claude-flow@v3alpha hooks route --task "[task]"
- + npx claude-flow@v3alpha hooks explain --topic "[topic]"
- + npx claude-flow@v3alpha hooks pretrain --model-type moe --epochs 10
- + npx claude-flow@v3alpha hooks build-agents --agent-types coder,tester
- + npx claude-flow@v3alpha hooks worker list
- + npx claude-flow@v3alpha hooks worker dispatch --trigger audit
- + npx claude-flow@v3alpha hooks worker status
- + node .claude/helpers/auto-memory-hook.mjs import-all
- + npm publish
- + npm version 3.7.1 --no-git-tag-version
- + npm dist-tag add @claude-flow/cli@3.7.1 alpha
- npm run build
Section tags
7 shared · 3 only in A · 5 only in B- − test
- − types
- − database
- + testing-strategy
- + security
- + dependencies
- + api
- + do-not
- setup
- build
- lint-format
- code-style
- architecture
- performance
- agent-behaviour
Line diff
ruvnet/ruflo · ruflo/src/ruvocal/CLAUDE.md
@@ −1 @@
1# CLAUDE.md
2
3This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
5## Overview
6
7Chat UI is a SvelteKit application that provides a chat interface for LLMs. It powers HuggingChat (hf.co/chat). The app speaks exclusively to OpenAI-compatible APIs via `OPENAI_BASE_URL`.
8
9## Commands
10
11```bash
12npm run dev # Start dev server on localhost:5173
13npm run build # Production build
14npm run preview # Preview production build
15npm run check # TypeScript validation (svelte-kit sync + svelte-check)
16npm run lint # Check formatting (Prettier) and linting (ESLint)
17npm run format # Auto-format with Prettier
18npm run test # Run all tests (Vitest)
19```
20
21### Running a Single Test
22
23```bash
24npx vitest run path/to/file.spec.ts # Run specific test file
25npx vitest run -t "test name" # Run test by name
26npx vitest --watch path/to/file.spec.ts # Watch mode for single file
27```
28
29### Test Environments
30
31Tests are split into three workspaces (configured in vite.config.ts):
32
33- **Client tests** (`*.svelte.test.ts`): Browser environment with Playwright
34- **SSR tests** (`*.ssr.test.ts`): Node environment for server-side rendering
35- **Server tests** (`*.test.ts`, `*.spec.ts`): Node environment for utilities
36
37## Architecture
38
39### Stack
40
41- **SvelteKit 2** with Svelte 5 (uses runes: `$state`, `$effect`, `$bindable`)
42- **MongoDB** for persistence (auto-fallback to in-memory with MongoMemoryServer when `MONGODB_URL` not set)
43- **TailwindCSS** for styling
44
45### Key Directories
46
47```
48src/
49├── lib/
50│ ├── components/ # Svelte components (chat/, mcp/, voice/, icons/)
51│ ├── server/
52│ │ ├── api/utils/ # Shared API helpers (auth, superjson, model/conversation resolvers)
53│ │ ├── textGeneration/ # LLM streaming pipeline
54│ │ ├── mcp/ # Model Context Protocol integration
55│ │ ├── router/ # Smart model routing (Omni)
56│ │ ├── database.ts # MongoDB collections
57│ │ ├── models.ts # Model registry from OPENAI_BASE_URL/models
58│ │ └── auth.ts # OpenID Connect authentication
59│ ├── types/ # TypeScript interfaces (Conversation, Message, User, Model, etc.)
60│ ├── stores/ # Svelte stores for reactive state
61│ └── utils/ # Helpers (tree/, marked.ts, auth.ts, etc.)
62├── routes/ # SvelteKit file-based routing
63│ ├── conversation/[id]/ # Chat page + streaming endpoint
64│ ├── settings/ # User settings pages
65│ ├── api/ # Legacy v1 API endpoints (mcp, transcribe, fetch-url)
66│ ├── api/v2/ # REST API endpoints (+server.ts)
67│ └── r/[id]/ # Shared conversation view
68```
69
70### Text Generation Flow
71
721. User sends message via `POST /conversation/[id]`
732. Server validates user, fetches conversation history
743. Builds message tree structure (see `src/lib/utils/tree/`)
754. Calls LLM endpoint via OpenAI client
765. Streams response back, stores in MongoDB
77
78### Model Context Protocol (MCP)
79
80MCP servers are configured via `MCP_SERVERS` env var. When enabled, tools are exposed as OpenAI function calls. The router can auto-select tools-capable models when `LLM_ROUTER_ENABLE_TOOLS=true`.
81
82### LLM Router (Omni)
83
84Smart routing via Arch-Router model. Configured with:
85
86- `LLM_ROUTER_ROUTES_PATH`: JSON file defining routes
87- `LLM_ROUTER_ARCH_BASE_URL`: Router endpoint
88- Shortcuts: multimodal routes bypass router if `LLM_ROUTER_ENABLE_MULTIMODAL=true`
89
90### Database Collections
91
92- `conversations` - Chat sessions with nested messages
93- `users` - User accounts (OIDC-backed)
94- `sessions` - Session data
95- `sharedConversations` - Public share links
96- `settings` - User preferences
97
98## Environment Setup
99
100Copy `.env` to `.env.local` and configure:
101
102```env
103OPENAI_BASE_URL=https://router.huggingface.co/v1
104OPENAI_API_KEY=hf_***
105# MONGODB_URL is optional; omit for in-memory DB persisted to ./db
106```
107
108See `.env` for full list of variables including router config, MCP servers, auth, and feature flags.
109
110## Code Conventions
111
112- TypeScript strict mode enabled
113- ESLint: no `any`, no non-null assertions
114- Prettier: tabs, 100 char width, Tailwind class sorting
115- Server vs client separation via SvelteKit conventions (`+page.server.ts` vs `+page.ts`)
116
117## Feature Development Checklist
118
119When building new features, consider:
120
1211. **HuggingChat vs self-hosted**: Wrap HuggingChat-specific features with `publicConfig.isHuggingChat`
1222. **Settings persistence**: Add new fields to `src/lib/types/Settings.ts`, update API endpoint at `src/routes/api/v2/user/settings/+server.ts`
1233. **Rich dropdowns**: Use `bits-ui` (Select, DropdownMenu) instead of native elements when you need icons/images in options
1244. **Scrollbars**: Use `scrollbar-custom` class for styled scrollbars
1255. **Icons**: Custom icons in `$lib/components/icons/`, use Carbon (`~icons/carbon/*`) or Lucide (`~icons/lucide/*`) for standard icons
1266. **Provider avatars**: Use `PROVIDERS_HUB_ORGS` from `@huggingface/inference` for HF provider avatar URLs
127
ruvnet/ruflo · CLAUDE.md
@@ +1 @@
1# Claude Code Configuration - Ruflo V3
2
3> Public release train: `@claude-flow/cli`, `claude-flow`, and `ruflo`.
4> Use package manifests and the registry as version truth; do not copy stale
5> version or capability counts into agent guidance.
6
7## Behavioral Rules (Always Enforced)
8
9- Do what has been asked; nothing more, nothing less
10- NEVER create files unless they're absolutely necessary for achieving your goal
11- ALWAYS prefer editing an existing file to creating a new one
12- NEVER proactively create documentation files (*.md) or README files unless explicitly requested
13- NEVER save working files, text/mds, or tests to the root folder
14- Never continuously check status after spawning a swarm — wait for results
15- ALWAYS read a file before editing it
16- NEVER commit secrets, credentials, or .env files
17
18## Capability Brain and Governed Implementation
19
20Ruflo is the coordination ledger and policy decision point. Claude Code
21executes code, tests, commands, and file changes. A Ruflo coordination call
22records work; it does not perform the implementation.
23
24When registered, call
25`guidance_brain({ mode: "recommend", task: "..." })` before complex Ruflo
26work. Use its live registry rather than guessing tool names. Treat
27`registered`, `configured`, `reachable`, `healthy`, and `authorized` as
28separate facts. If unavailable, continue with compatible guidance tools, CLI
29discovery, and these repository instructions.
30
31Use this loop: recall → inspect → route → plan → execute → test → validate →
32benchmark → optimize → receipt → handoff → separately authorized publish.
33
34## File Organization
35
36- NEVER save to root folder — use the directories below
37- Use `/src` for source code files
38- Use `/tests` for test files
39- Use `/docs` for documentation and markdown files
40- Use `/config` for configuration files
41- Use `/scripts` for utility scripts
42- Use `/examples` for example code
43
44## Project Architecture
45
46- Follow Domain-Driven Design with bounded contexts
47- Keep files under 500 lines
48- Use typed interfaces for all public APIs
49- Prefer TDD London School (mock-first) for new code
50- Use event sourcing for state changes
51- Ensure input validation at system boundaries
52
53### Key Packages
54
55| Package | Path | Purpose |
56|---------|------|---------|
57| `@claude-flow/cli` | `v3/@claude-flow/cli/` | CLI entry point (26 commands) |
58| `@claude-flow/codex` | `v3/@claude-flow/codex/` | Dual-mode Claude + Codex collaboration |
59| `@claude-flow/guidance` | `v3/@claude-flow/guidance/` | Governance control plane |
60| `@claude-flow/hooks` | `v3/@claude-flow/hooks/` | 17 hooks + 12 workers |
61| `@claude-flow/memory` | `v3/@claude-flow/memory/` | AgentDB + HNSW search |
62| `@claude-flow/security` | `v3/@claude-flow/security/` | Input validation, CVE remediation |
63
64## Concurrent Automated Development
65
66- Parallelize independent research, tests, reviews, and non-overlapping
67 implementation.
68- Never allow two writers in one worktree. Give every writing agent an isolated
69 worktree and explicit file ownership.
70- Read-only agents may share a checkout; writing agents may not.
71- Only the integration owner edits shared manifests and lockfiles or reconciles
72 overlapping changes.
73- Continue independent local work after spawning agents; wait only when a real
74 dependency blocks progress. Do not repeatedly poll.
75- A lease or work claim coordinates ownership; it never grants authority.
76- Bind tests, benchmarks, policy decisions, and handoffs to an exact clean
77 commit or immutable dirty-worktree snapshot.
78- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose and
79 evaluate candidates, but cannot self-promote or expand tools, network,
80 secrets, spend, concurrency, or release authority.
81
82---
83
84## Swarm Orchestration
85
86- MUST initialize the swarm using MCP tools when starting complex tasks
87- MUST spawn concurrent agents using Claude Code's Task tool
88- Never use MCP tools alone for execution — Task tool agents do the actual work
89
90### MCP + Task Tool in SAME Message
91
92- MUST call MCP tools AND Task tool in ONE message for complex work
93- Always call MCP first, then IMMEDIATELY call Task tool to spawn agents
94
95### 3-Tier Model Routing (ADR-026, ADR-143)
96
97| Tier | Handler | Latency | Cost | Use Cases |
98|------|---------|---------|------|-----------|
99| **1** | Deterministic codemod | ~1ms | $0 | Structural transforms with **no LLM**: `var-to-const`, `remove-console`, `add-logging` |
100| **2** | Haiku | ~500ms | $0.0002 | Simple tasks, low complexity (<30%) |
101| **3** | Sonnet/Opus | 2-5s | $0.003-0.015 | Complex reasoning, architecture, security (>30%) |
102
103- Always check for `[CODEMOD_AVAILABLE]` or `[TASK_MODEL_RECOMMENDATION]` before spawning agents
104- When you see `[CODEMOD_AVAILABLE]`, call the `hooks_codemod` MCP tool (intent + file) — it applies the transform deterministically via the TypeScript compiler at $0, no LLM. Deterministic intents only: `var-to-const`, `remove-console`, `add-logging`
105- `add-types`, `add-error-handling`, `async-await` need judgement and route to a model (Tier 2/3) — they are **not** $0 codemods (see ADR-143)
106- Agent Booster (`agent-booster`) is a fast-apply merge engine for arbitrary LLM-produced edit snippets, not an intent-transform engine — it is **not** the Tier-1 path
107
108## Swarm Configuration & Anti-Drift
109
110### Anti-Drift Coding Swarm (PREFERRED DEFAULT)
111
112- ALWAYS use hierarchical topology for coding swarms
113- Keep maxAgents at 6-8 for tight coordination
114- Use specialized strategy for clear role boundaries
115- Use `raft` consensus for hive-mind (leader maintains authoritative state)
116- Run frequent checkpoints via `post-task` hooks
117- Keep shared memory namespace for all agents
118- Keep task cycles short with verification gates
119
120```javascript
121mcp__ruv-swarm__swarm_init({
122 topology: "hierarchical",
123 maxAgents: 8,
124 strategy: "specialized"
125})
126```
127
128## Dual-Mode Collaboration (Claude Code + Codex)
129
130This 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.
131
132### Why Dual-Mode?
133
134| Single Platform | Dual-Mode Collaboration |
135|----------------|------------------------|
136| One model's perspective | Two AI platforms cross-validating |
137| Limited reasoning styles | Complementary strengths |
138| No external verification | Built-in code review |
139| Sequential workflows | Parallel execution |
140
141### Dual-Mode Swarm Protocol
142
143For complex tasks, spawn both Claude and Codex workers in parallel:
144
145```javascript
146// STEP 1: Initialize dual-mode swarm
147mcp__ruv-swarm__swarm_init({
148 topology: "hierarchical",
149 maxAgents: 8,
150 strategy: "specialized"
151})
152
153// STEP 2: Spawn BOTH platforms in parallel via Task tool
154// 🔵 Claude Code workers (architecture, security, testing)
155Task("Architect", "Design the implementation. Store design in memory namespace 'collaboration'.", "system-architect")
156Task("Tester", "Write tests based on architect's design. Read from 'collaboration' namespace.", "tester")
157Task("Reviewer", "Review code quality and security. Store findings in 'collaboration'.", "reviewer")
158
159// 🟢 Codex workers (implementation, optimization)
160// Spawn via CLI for Codex platform
161Bash("npx claude-flow-codex dual run --worker 'codex:coder:Implement the solution based on architect design' --namespace collaboration")
162Bash("npx claude-flow-codex dual run --worker 'codex:optimizer:Optimize performance based on implementation' --namespace collaboration")
163
164// STEP 3: Coordinate via shared memory
165Bash("npx claude-flow@v3alpha memory store --namespace collaboration --key 'task-context' --value '[task description]'")
166```
167
168### Collaboration Templates (Pre-Built Pipelines)
169
170| Template | Workers | Pipeline |
171|----------|---------|----------|
172| `feature` | 🔵 Architect → 🟢 Coder → 🔵 Tester → 🟢 Reviewer | Full feature development |
173| `security` | 🔵 Analyst → 🟢 Scanner → 🔵 Reporter | Security audit workflow |
174| `refactor` | 🔵 Architect → 🟢 Refactorer → 🔵 Tester | Code modernization |
175| `bugfix` | 🔵 Researcher → 🟢 Coder → 🔵 Tester | Bug investigation & fix |
176
177### Dual-Mode CLI Commands
178
179```bash
180# Run a collaboration template
181npx claude-flow-codex dual run feature --task "Add user authentication with OAuth"
182npx claude-flow-codex dual run security --target "./src"
183npx claude-flow-codex dual run refactor --target "./src/legacy"
184
185# Custom multi-platform swarm
186npx claude-flow-codex dual run \
187 --worker "claude:architect:Design the API structure" \
188 --worker "codex:coder:Implement REST endpoints" \
189 --worker "claude:tester:Write integration tests" \
190 --worker "codex:reviewer:Review code quality" \
191 --namespace "api-feature"
192
193# Check collaboration status
194npx claude-flow-codex dual status
195
196# List available templates
197npx claude-flow-codex dual templates
198```
199
200### Shared Memory Coordination
201
202All workers share state via the `collaboration` namespace:
203
204```bash
205# Store context for cross-platform sharing
206npx claude-flow@v3alpha memory store --namespace collaboration --key "design-decisions" --value "..."
207
208# Search for patterns across all workers
209npx claude-flow@v3alpha memory search --namespace collaboration --query "authentication patterns"
210
211# Retrieve specific findings
212npx claude-flow@v3alpha memory retrieve --namespace collaboration --key "security-findings"
213```
214
215### Cross-Platform Learning
216
217Both platforms learn from each other's outputs:
218
219```bash
220# After successful collaboration, train patterns
221npx claude-flow@v3alpha hooks post-task --task-id "dual-[id]" --success true --train-neural true
222
223# Store successful collaboration patterns
224npx claude-flow@v3alpha memory store --namespace patterns --key "dual-mode-[pattern]" --value "[what worked]"
225
226# Transfer learnings to both platforms
227npx claude-flow@v3alpha hooks transfer store --pattern "dual-collab-success"
228```
229
230### Worker Dependency Levels
231
232Workers execute in dependency order:
233
234```
235Level 0: [🔵 Architect] # No dependencies - runs first
236Level 1: [🟢 Coder, 🔵 Tester] # Depends on Architect
237Level 2: [🔵 Reviewer] # Depends on Coder + Tester
238Level 3: [🟢 Optimizer] # Depends on Reviewer approval
239```
240
241### Platform Strengths
242
243| Task Type | Preferred Platform | Reason |
244|-----------|-------------------|--------|
245| Architecture & Design | 🔵 Claude | Strong reasoning, system thinking |
246| Implementation | 🟢 Codex | Fast code generation |
247| Security Review | 🔵 Claude | Careful analysis, threat modeling |
248| Performance Optimization | 🟢 Codex | Code-level optimizations |
249| Testing Strategy | 🔵 Claude | Coverage analysis, edge cases |
250| Refactoring | 🟢 Codex | Bulk code transformations |
251
252### Programmatic API
253
254```typescript
255import { DualModeOrchestrator, CollaborationTemplates } from '@claude-flow/codex';
256
257const orchestrator = new DualModeOrchestrator({
258 namespace: 'my-feature',
259 memoryBackend: 'hybrid'
260});
261
262// Use pre-built template
263const workers = CollaborationTemplates.featureDevelopment('Add OAuth login');
264
265// Run collaboration
266const results = await orchestrator.runCollaboration(workers, 'Implement OAuth feature');
267
268// Access shared memory
269const designDocs = await orchestrator.getMemory('design-decisions');
270```
271
272---
273
274## Swarm Protocols & Routing
275
276### Auto-Start Swarm Protocol
277
278When the user requests a complex task (multi-file changes, feature implementation, refactoring), **immediately execute this pattern in a SINGLE message:**
279
280```javascript
281// STEP 1: Initialize swarm coordination via MCP
282mcp__ruv-swarm__swarm_init({
283 topology: "hierarchical",
284 maxAgents: 8,
285 strategy: "specialized"
286})
287
288// STEP 2: Spawn NAMED agents concurrently — all in ONE message
289// Each agent knows WHO to message next in the pipeline
290Task({
291 prompt: "Research requirements and codebase. SendMessage findings to 'architect' when done.",
292 subagent_type: "researcher", name: "researcher", run_in_background: true
293})
294Task({
295 prompt: "Wait for research from 'researcher'. Design implementation. SendMessage design to 'coder'.",
296 subagent_type: "system-architect", name: "architect", run_in_background: true
297})
298Task({
299 prompt: "Wait for design from 'architect'. Implement the solution. SendMessage code paths to 'tester'.",
300 subagent_type: "coder", name: "coder", run_in_background: true
301})
302Task({
303 prompt: "Wait for implementation from 'coder'. Write tests. SendMessage results to 'reviewer'.",
304 subagent_type: "tester", name: "tester", run_in_background: true
305})
306Task({
307 prompt: "Wait for test results from 'tester'. Review code quality and security. Report findings.",
308 subagent_type: "reviewer", name: "reviewer", run_in_background: true
309})
310
311// STEP 3: Kick off the pipeline
312SendMessage({ to: "researcher", summary: "Start research", message: "[task description and context]" })
313
314// STEP 4: Batch todos
315TodoWrite({ todos: [
316 {content: "Research and analyze requirements", status: "in_progress", activeForm: "Researching"},
317 {content: "Design architecture", status: "pending", activeForm: "Designing"},
318 {content: "Implement solution", status: "pending", activeForm: "Implementing"},
319 {content: "Write tests", status: "pending", activeForm: "Testing"},
320 {content: "Review and finalize", status: "pending", activeForm: "Reviewing"}
321]})
322
323// Pipeline flow via SendMessage:
324// researcher ──→ architect ──→ coder ──→ tester ──→ reviewer
325```
326
327### Agent Routing (Anti-Drift)
328
329| Code | Task | Agents |
330|------|------|--------|
331| 1 | Bug Fix | coordinator, researcher, coder, tester |
332| 3 | Feature | coordinator, architect, coder, tester, reviewer |
333| 5 | Refactor | coordinator, architect, coder, reviewer |
334| 7 | Performance | coordinator, perf-engineer, coder |
335| 9 | Security | coordinator, security-architect, auditor |
336| 11 | Memory | coordinator, memory-specialist, perf-engineer |
337| 13 | Docs | researcher, api-docs |
338
339**Codes 1-11: hierarchical/specialized (anti-drift). Code 13: mesh/balanced**
340
341### Task Complexity Detection
342
343**AUTO-INVOKE SWARM when task involves:**
344- Multiple files (3+)
345- New feature implementation
346- Refactoring across modules
347- API changes with tests
348- Security-related changes
349- Performance optimization
350- Database schema changes
351
352**SKIP SWARM for:**
353- Single file edits
354- Simple bug fixes (1-2 lines)
355- Documentation updates
356- Configuration changes
357- Quick questions/exploration
358
359## Project Configuration
360
361This project is configured with Claude Flow V3 (Anti-Drift Defaults):
362- **Topology**: hierarchical (prevents drift via central coordination)
363- **Max Agents**: 8 (smaller team = less drift)
364- **Strategy**: specialized (clear roles, no overlap)
365- **Consensus**: raft (leader maintains authoritative state)
366- **Memory Backend**: hybrid (SQLite + AgentDB)
367- **HNSW Indexing**: Enabled (measured ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force; ANN wins above the crossover)
368- **Neural Learning**: Enabled (SONA)
369
370## V3 CLI Commands (26 Commands, 140+ Subcommands)
371
372### Core Commands
373
374| Command | Subcommands | Description |
375|---------|-------------|-------------|
376| `init` | 4 | Project initialization with wizard, presets, skills, hooks |
377| `agent` | 8 | Agent lifecycle (spawn, list, status, stop, metrics, pool, health, logs) |
378| `swarm` | 6 | Multi-agent swarm coordination and orchestration |
379| `memory` | 11 | AgentDB memory with HNSW vector search (measured ~1.9x–4.7x vs brute force above crossover) |
380| `mcp` | 9 | MCP server management and tool execution |
381| `task` | 6 | Task creation, assignment, and lifecycle |
382| `session` | 7 | Session state management and persistence |
383| `config` | 7 | Configuration management and provider setup |
384| `status` | 3 | System status monitoring with watch mode |
385| `start` | 3 | Service startup and quick launch |
386| `workflow` | 6 | Workflow execution and template management |
387| `hooks` | 17 | Self-learning hooks + 12 background workers |
388| `hive-mind` | 6 | Queen-led Byzantine fault-tolerant consensus |
389
390### Advanced Commands
391
392| Command | Subcommands | Description |
393|---------|-------------|-------------|
394| `daemon` | 5 | Background worker daemon (start, stop, status, trigger, enable) |
395| `neural` | 5 | Neural pattern training (train, status, patterns, predict, optimize) |
396| `security` | 6 | Security scanning (scan, audit, cve, threats, validate, report) |
397| `performance` | 5 | Performance profiling (benchmark, profile, metrics, optimize, report) |
398| `providers` | 5 | AI providers (list, add, remove, test, configure) |
399| `plugins` | 5 | Plugin management (list, install, uninstall, enable, disable) |
400| `deployment` | 5 | Deployment management (deploy, rollback, status, environments, release) |
401| `embeddings` | 4 | Vector embeddings (embed, batch, search, init) — agentic-flow ONNX backend (speedup unverified, no benchmark) |
402| `claims` | 4 | Claims-based authorization (check, grant, revoke, list) |
403| `migrate` | 5 | V2 to V3 migration with rollback support |
404| `process` | 4 | Background process management |
405| `doctor` | 1 | System diagnostics with health checks |
406| `completions` | 4 | Shell completions (bash, zsh, fish, powershell) |
407
408### Quick CLI Examples
409
410```bash
411# Initialize project
412npx claude-flow@v3alpha init --wizard
413
414# Start daemon with background workers
415npx claude-flow@v3alpha daemon start
416
417# Spawn an agent
418npx claude-flow@v3alpha agent spawn -t coder --name my-coder
419
420# Initialize swarm
421npx claude-flow@v3alpha swarm init --v3-mode
422
423# Search memory (HNSW-indexed)
424npx claude-flow@v3alpha memory search -q "authentication patterns"
425
426# System diagnostics
427npx claude-flow@v3alpha doctor --fix
428
429# Security scan
430npx claude-flow@v3alpha security scan --depth full
431
432# Performance benchmark
433npx claude-flow@v3alpha performance benchmark --suite all
434```
435
436## Headless Background Instances (claude -p)
437
438Use `claude -p` (print/pipe mode) to spawn headless Claude instances for parallel background work. These run non-interactively and return results to stdout.
439
440### Basic Usage
441
442```bash
443# Single headless task
444claude -p "Analyze the authentication module for security issues"
445
446# With model selection
447claude -p --model haiku "Format this config file"
448claude -p --model opus "Design the database schema for user management"
449
450# With output format
451claude -p --output-format json "List all TODO comments in src/"
452claude -p --output-format stream-json "Refactor the error handling in api.ts"
453
454# With budget limits
455claude -p --max-budget-usd 0.50 "Run comprehensive security audit"
456
457# With specific tools allowed
458claude -p --allowedTools "Read,Grep,Glob" "Find all files that import the auth module"
459
460# Skip permissions (sandboxed environments only)
461claude -p --dangerously-skip-permissions "Fix all lint errors in src/"
462```
463
464### Parallel Background Execution
465
466```bash
467# Spawn multiple headless instances in parallel
468claude -p "Analyze src/auth/ for vulnerabilities" &
469claude -p "Write tests for src/api/endpoints.ts" &
470claude -p "Review src/models/ for performance issues" &
471wait # Wait for all to complete
472
473# With results captured
474SECURITY=$(claude -p "Security audit of auth module" &)
475TESTS=$(claude -p "Generate test coverage report" &)
476PERF=$(claude -p "Profile memory usage in workers" &)
477wait
478echo "$SECURITY" "$TESTS" "$PERF"
479```
480
481### Session Continuation
482
483```bash
484# Start a task, resume later
485claude -p --session-id "abc-123" "Start analyzing the codebase"
486claude -p --resume "abc-123" "Continue with the test files"
487
488# Fork a session for parallel exploration
489claude -p --resume "abc-123" --fork-session "Try approach A: event sourcing"
490claude -p --resume "abc-123" --fork-session "Try approach B: CQRS pattern"
491```
492
493### Key Flags
494
495| Flag | Purpose |
496|------|---------|
497| `-p, --print` | Non-interactive mode, print and exit |
498| `--model <model>` | Select model (haiku, sonnet, opus) |
499| `--output-format <fmt>` | Output: text, json, stream-json |
500| `--max-budget-usd <amt>` | Spending cap per invocation |
501| `--allowedTools <tools>` | Restrict available tools |
502| `--append-system-prompt` | Add custom instructions |
503| `--resume <id>` | Continue a previous session |
504| `--fork-session` | Branch from resumed session |
505| `--fallback-model <model>` | Auto-fallback if primary overloaded |
506| `--permission-mode <mode>` | acceptEdits, bypassPermissions, plan, etc. |
507| `--mcp-config <json>` | Load MCP servers from JSON |
508
509## Available Agents (60+ Types)
510
511### Core Development
512`coder`, `reviewer`, `tester`, `planner`, `researcher`
513
514### V3 Specialized Agents
515`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`
516
517### @claude-flow/security Module
518CVE remediation, input validation, path security:
519- `InputValidator` — Zod-based validation at boundaries
520- `PathValidator` — Path traversal prevention
521- `SafeExecutor` — Command injection protection
522- `PasswordHasher` — bcrypt hashing
523- `TokenGenerator` — Secure token generation
524
525### Token Optimizer (Agent Booster)
526Integrates agentic-flow optimizations for 30-50% token reduction:
527```typescript
528import { getTokenOptimizer } from '@claude-flow/integration';
529const optimizer = await getTokenOptimizer();
530
531// Compact context (32% fewer tokens)
532const ctx = await optimizer.getCompactContext("auth patterns");
533
534// 352x faster edits = fewer retries
535await optimizer.optimizedEdit(file, old, new, "typescript");
536
537// Optimal config (100% success rate)
538const config = optimizer.getOptimalConfig(agentCount);
539```
540| Feature | Token Savings |
541|---------|---------------|
542| ReasoningBank retrieval | -32% |
543| Agent Booster edits | -15% |
544| Cache (95% hit rate) | -10% |
545| Optimal batch size | -20% |
546
547### Swarm Coordination
548`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`, `collective-intelligence-coordinator`, `swarm-memory-manager`
549
550### Consensus & Distributed
551`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`, `consensus-builder`, `crdt-synchronizer`, `quorum-manager`, `security-manager`
552
553### Performance & Optimization
554`perf-analyzer`, `performance-benchmarker`, `task-orchestrator`, `memory-coordinator`, `smart-agent`
555
556### GitHub & Repository
557`github-modes`, `pr-manager`, `code-review-swarm`, `issue-tracker`, `release-manager`, `workflow-automation`, `project-board-sync`, `repo-architect`, `multi-repo-swarm`
558
559### SPARC Methodology
560`sparc-coord`, `sparc-coder`, `specification`, `pseudocode`, `architecture`, `refinement`
561
562### Specialized Development
563`backend-dev`, `mobile-dev`, `ml-developer`, `cicd-engineer`, `api-docs`, `system-architect`, `code-analyzer`, `base-template-generator`
564
565### Testing & Validation
566`tdd-london-swarm`, `production-validator`
567
568## Agent Teams & Comms System
569
570Agent 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.
571
572### Architecture
573
574```
575Team Lead (you)
576 ├── SendMessage ←→ architect (named agent)
577 ├── SendMessage ←→ developer (named agent)
578 ├── SendMessage ←→ tester (named agent)
579 └── SendMessage ←→ reviewer (named agent)
580 ↕ agents can message each other by name
581```
582
583### Core Principle: Named Agents + SendMessage
584
585Every agent MUST have a `name` so it's addressable. Communication happens via `SendMessage`, not polling or shared memory.
586
587```javascript
588// STEP 1: Spawn named agents (all in ONE message, background)
589Task({
590 prompt: "Design the API. When done, send your design to 'developer' via SendMessage.",
591 subagent_type: "system-architect",
592 name: "architect",
593 run_in_background: true
594})
595Task({
596 prompt: "Wait for architect's design via SendMessage. Then implement it. Send code to 'tester'.",
597 subagent_type: "coder",
598 name: "developer",
599 run_in_background: true
600})
601Task({
602 prompt: "Wait for developer's code via SendMessage. Write tests. Send results to 'reviewer'.",
603 subagent_type: "tester",
604 name: "tester",
605 run_in_background: true
606})
607
608// STEP 2: Kick off the pipeline by messaging the first agent
609SendMessage({
610 to: "architect",
611 summary: "Start API design",
612 message: "Design a REST API for user management with CRUD endpoints. Send the design to 'developer' when done."
613})
614```
615
616### SendMessage Protocol
617
618```javascript
619// Lead → Teammate: assign work
620SendMessage({ to: "developer", summary: "Implement auth", message: "Build OAuth2 flow..." })
621
622// Lead → Teammate: redirect priorities
623SendMessage({ to: "developer", summary: "Prioritize auth", message: "Auth endpoint is blocking tester, do it first." })
624
625// Lead → Teammate: provide context from another agent's results
626SendMessage({ to: "tester", summary: "Architect output", message: "The architect designed these endpoints: [details]. Write tests for them." })
627
628// Lead → Teammate: graceful shutdown
629SendMessage({ to: "developer", message: { type: "shutdown_request" } })
630```
631
632### Coordination Patterns
633
634**Pipeline (A → B → C)** — each agent messages the next when done:
635```
636architect ──SendMessage──→ developer ──SendMessage──→ tester ──SendMessage──→ reviewer
637```
638Tell each agent WHO to message next in their prompt.
639
640**Fan-out / Fan-in** — lead spawns parallel agents, collects results:
641```
642 ┌→ researcher-1 ──→┐
643lead ────┼→ researcher-2 ──→├──→ lead synthesizes
644 └→ researcher-3 ──→┘
645```
646Spawn with `run_in_background: true`. Results arrive as task completions.
647
648**Supervisor / Worker** — lead assigns, workers report back:
649```
650lead ←──SendMessage──→ worker-1
651lead ←──SendMessage──→ worker-2
652lead ←──SendMessage──→ worker-3
653```
654Lead sends tasks via SendMessage, workers respond with results.
655
656### Agent Prompt Template (Comms-Aware)
657
658When spawning agents that need to coordinate, include comms instructions:
659
660```javascript
661Task({
662 prompt: `You are the architect for this feature team.
663
664YOUR TASK: Design the database schema for user management.
665
666COMMS PROTOCOL:
667- When your design is ready, send it to "developer" via SendMessage
668- If you need clarification, message the team lead (just output text)
669- Include file paths and key decisions in your message
670
671DELIVERABLE: Schema design with entity relationships, indexes, and migration plan.`,
672 subagent_type: "system-architect",
673 name: "architect",
674 run_in_background: true
675})
676```
677
678### Full Team Spawn Example
679
680```javascript
681// Create shared task list first
682TaskCreate({ subject: "Design schema", description: "...", activeForm: "Designing" })
683TaskCreate({ subject: "Implement models", description: "...", activeForm: "Implementing" })
684TaskCreate({ subject: "Write tests", description: "...", activeForm: "Testing" })
685TaskCreate({ subject: "Security review", description: "...", activeForm: "Reviewing" })
686
687// Spawn ALL named agents in ONE message
688Task({
689 prompt: "Design the schema. SendMessage to 'developer' with your design when done. Update task #1.",
690 subagent_type: "system-architect", name: "architect", run_in_background: true
691})
692Task({
693 prompt: "Wait for schema from 'architect'. Implement models + endpoints. SendMessage to 'tester'. Update task #2.",
694 subagent_type: "coder", name: "developer", run_in_background: true
695})
696Task({
697 prompt: "Wait for code from 'developer'. Write integration tests. SendMessage results to 'security'. Update task #3.",
698 subagent_type: "tester", name: "tester", run_in_background: true
699})
700Task({
701 prompt: "Wait for test results from 'tester'. Review for vulnerabilities. Update task #4.",
702 subagent_type: "security-auditor", name: "security", run_in_background: true
703})
704```
705
706### Agent Teams Hooks
707
708| Hook | Trigger | Purpose |
709|------|---------|---------|
710| `TeammateIdle` | Teammate finishes turn | Auto-assign pending tasks via SendMessage |
711| `TaskCompleted` | Task marked complete | Train patterns, notify lead via SendMessage |
712
713```bash
714npx claude-flow@v3alpha hooks teammate-idle --auto-assign true
715npx claude-flow@v3alpha hooks task-completed -i task-123 --train-patterns true
716```
717
718### Rules
719
7201. **Always name agents** — use `name: "role-name"` so they're addressable
7212. **Comms over memory** — use SendMessage for real-time coordination, memory for persistence
7223. **Pipeline prompts** — tell each agent WHO to message next and WHAT to send
7234. **Spawn all at once** — all Task calls in ONE message with `run_in_background: true`
7245. **Don't poll** — agents message back when done; wait for task completion notifications
7256. **Graceful shutdown** — send `{ type: "shutdown_request" }` before TeamDelete
7267. **Lead synthesizes** — when agents complete, review ALL results before responding to user
727
728## V3 Hooks System (17 Hooks + 12 Workers)
729
730### Hook Categories
731
732| Category | Hooks | Purpose |
733|----------|-------|---------|
734| **Core** | `pre-edit`, `post-edit`, `pre-command`, `post-command`, `pre-task`, `post-task` | Tool lifecycle |
735| **Session** | `session-start`, `session-end`, `session-restore`, `notify` | Context management |
736| **Intelligence** | `route`, `explain`, `pretrain`, `build-agents`, `transfer` | Neural learning |
737| **Learning** | `intelligence` (trajectory-start/step/end, pattern-store/search, stats, attention) | Reinforcement |
738| **Agent Teams** | `teammate-idle`, `task-completed` | Multi-agent coordination |
739
740### 12 Background Workers
741
742| Worker | Priority | Description |
743|--------|----------|-------------|
744| `ultralearn` | normal | Deep knowledge acquisition |
745| `optimize` | high | Performance optimization |
746| `consolidate` | low | Memory consolidation |
747| `predict` | normal | Predictive preloading |
748| `audit` | critical | Security analysis |
749| `map` | normal | Codebase mapping |
750| `preload` | low | Resource preloading |
751| `deepdive` | normal | Deep code analysis |
752| `document` | normal | Auto-documentation |
753| `refactor` | normal | Refactoring suggestions |
754| `benchmark` | normal | Performance benchmarking |
755| `testgaps` | normal | Test coverage analysis |
756
757### Essential Hook Commands
758
759```bash
760# Core hooks
761npx claude-flow@v3alpha hooks pre-task --description "[task]"
762npx claude-flow@v3alpha hooks post-task --task-id "[id]" --success true
763npx claude-flow@v3alpha hooks post-edit --file "[file]" --train-patterns
764
765# Session management
766npx claude-flow@v3alpha hooks session-start --session-id "[id]"
767npx claude-flow@v3alpha hooks session-end --export-metrics true
768npx claude-flow@v3alpha hooks session-restore --session-id "[id]"
769
770# Intelligence routing
771npx claude-flow@v3alpha hooks route --task "[task]"
772npx claude-flow@v3alpha hooks explain --topic "[topic]"
773
774# Neural learning
775npx claude-flow@v3alpha hooks pretrain --model-type moe --epochs 10
776npx claude-flow@v3alpha hooks build-agents --agent-types coder,tester
777
778# Background workers
779npx claude-flow@v3alpha hooks worker list
780npx claude-flow@v3alpha hooks worker dispatch --trigger audit
781npx claude-flow@v3alpha hooks worker status
782```
783
784## Intelligence System (RuVector)
785
786V3 includes the RuVector Intelligence System (measured numbers: see [audit](docs/reviews/intelligence-system-audit-2026-05-29.md) + [`scripts/benchmark-intelligence.mjs`](scripts/benchmark-intelligence.mjs)):
787- **SONA**: Self-Optimizing Neural Architecture (measured 0.0043ms/adapt, target <0.05ms met)
788- **MoE**: Mixture of Experts for specialized routing (gate converges — confidence 0.13→0.88 after rewards)
789- **HNSW**: measured ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force (recall@10 ~0.99); ANN wins above the crossover, ruvector NAPI backend (WASM not active on test host)
790- **EWC++**: Elastic Weight Consolidation (prevents forgetting)
791- **Flash Attention**: integration available; speedup dropped from docs pending an in-tree benchmark (was: 2.49x–7.47x, inherited unverified from upstream — removed to avoid a credibility claim we can't reproduce)
792
793The 4-step intelligence pipeline:
7941. **RETRIEVE** — Fetch relevant patterns via HNSW
7952. **JUDGE** — Evaluate with verdicts (success/failure)
7963. **DISTILL** — Extract key learnings via LoRA
7974. **CONSOLIDATE** — Prevent catastrophic forgetting via EWC++
798
799## Embeddings Package (v3.0.0-alpha.12)
800
801Features:
802- **sql.js**: Cross-platform SQLite persistent cache (WASM, no native compilation)
803- **Document chunking**: Configurable overlap and size
804- **Normalization**: L2, L1, min-max, z-score
805- **Hyperbolic embeddings**: Poincare ball model for hierarchical data
806- **agentic-flow ONNX integration**: speedup unverified (no benchmark; backend reported `onnx`, model all-MiniLM-L6-v2, 384-dim)
807- **Neural substrate**: Integration with RuVector
808
809## Hive-Mind Consensus
810
811### Topologies
812- `hierarchical` — Queen controls workers directly
813- `mesh` — Fully connected peer network
814- `hierarchical-mesh` — Hybrid (recommended)
815- `adaptive` — Dynamic based on load
816
817### Consensus Strategies
818- `byzantine` — BFT (tolerates f < n/3 faulty)
819- `raft` — Leader-based (tolerates f < n/2)
820- `gossip` — Epidemic for eventual consistency
821- `crdt` — Conflict-free replicated data types
822- `quorum` — Configurable quorum-based
823
824## V3 Performance Targets
825
826> 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".
827
828| Metric | Measured / Target | Status |
829|--------|-------------------|--------|
830| HNSW Search | ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force (recall@10 ~0.99); ties/loses below crossover | **Measured** (ruvector NAPI; 150x-12,500x NOT reproduced — was brute-force fallback) |
831| Int8 Quantization | 3.84x compression, reconstruction cosine 0.99999 | **Measured** |
832| RaBitQ Quantization | 32x compression, 0.60ms/query (14,760-vec index) | **Measured** |
833| SONA Adaptation | 0.0043ms/adapt (target <0.05ms met) | **Measured** |
834| MoE Gate | converges — confidence 0.13→0.88, Q 0→99.8 after rewards | **Measured** |
835| Flash Attention | integration available; measured speedup pending benchmark | **Not measured** — prior "2.49x–7.47x" figure was inherited from upstream marketing, never reproduced in-tree; dropped to avoid a credibility claim we can't verify |
836| MCP Response | <100ms | target |
837| CLI Startup | <500ms | target |
838
839## Environment Variables
840
841```bash
842# Configuration
843CLAUDE_FLOW_CONFIG=./claude-flow.config.json
844CLAUDE_FLOW_LOG_LEVEL=info
845
846# Provider API Keys
847ANTHROPIC_API_KEY=sk-ant-...
848OPENAI_API_KEY=sk-...
849GOOGLE_API_KEY=...
850
851# MCP Server
852CLAUDE_FLOW_MCP_PORT=3000
853CLAUDE_FLOW_MCP_HOST=localhost
854CLAUDE_FLOW_MCP_TRANSPORT=stdio
855
856# Memory
857CLAUDE_FLOW_MEMORY_BACKEND=hybrid
858CLAUDE_FLOW_MEMORY_PATH=./data/memory
859```
860
861## Doctor Health Checks
862
863Run `npx claude-flow@v3alpha doctor` to check:
864- Node.js version (20+)
865- npm version (9+)
866- Git installation
867- Config file validity
868- Daemon status
869- Memory database
870- API keys
871- MCP servers
872- Disk space
873- TypeScript installation
874
875## Quick Setup
876
877```bash
878# Add MCP servers
879claude mcp add claude-flow -- npx -y ruflo@latest mcp start
880claude mcp add ruv-swarm npx ruv-swarm mcp start # Optional
881claude mcp add flow-nexus npx flow-nexus@latest mcp start # Optional
882
883# Start daemon
884npx claude-flow@v3alpha daemon start
885
886# Run doctor
887npx claude-flow@v3alpha doctor --fix
888```
889
890## Claude Code vs MCP Tools
891
892### Claude Code Handles ALL EXECUTION:
893- **Task tool**: Spawn and run agents concurrently
894- File operations (Read, Write, Edit, MultiEdit, Glob, Grep)
895- Code generation and programming
896- Bash commands and system operations
897- TodoWrite and task management
898- Git operations
899
900### MCP Tools ONLY COORDINATE:
901- Swarm initialization (topology setup)
902- Agent type definitions
903- Task orchestration
904- Memory management
905- Neural features
906- Performance tracking
907
908- Keep MCP for coordination strategy only — use Claude Code's Task tool for real execution
909
910## Claude Code ↔ AgentDB Memory Bridge
911
912Claude Code's auto-memory (`~/.claude/projects/*/memory/*.md`) is bridged to AgentDB with ONNX vector embeddings for semantic search.
913
914### MCP Tools
915
916| Tool | Description |
917|------|-------------|
918| `memory_import_claude` | Import Claude Code memories into AgentDB with 384-dim ONNX embeddings. Use `allProjects: true` to import from ALL projects. |
919| `memory_bridge_status` | Show bridge health — Claude files, AgentDB entries, SONA state, connection status |
920| `memory_search_unified` | Semantic search across ALL namespaces (claude-memories, auto-memory, patterns, tasks, feedback) |
921
922### Auto-Import on Session Start
923
924The `SessionStart` hook automatically imports current project's memories into AgentDB. For manual import of all projects:
925
926```bash
927# Via MCP tool (from Claude Code)
928memory_import_claude({ allProjects: true })
929
930# Via helper hook (from terminal)
931node .claude/helpers/auto-memory-hook.mjs import-all
932```
933
934### Unified Search
935
936Search across both Claude Code memories and AgentDB entries:
937
938```bash
939# Via MCP tool
940memory_search_unified({ query: "authentication security", limit: 5 })
941
942# Results include source attribution: claude-code, auto-memory, or agentdb
943```
944
945### Intelligence Pipeline
946
947| Component | Status | Details |
948|-----------|--------|---------|
949| ONNX Embeddings | Active | all-MiniLM-L6-v2, 384 dimensions |
950| SONA Learning | Active | Pattern matching + trajectory recording |
951| ReasoningBank | Active | Pattern storage with file persistence |
952| AgentDB sql.js | Active | SQLite with vector_indexes table |
953
954## Publishing to npm
955
956### Versioning policy (stable releases — alpha series ended at 3.7.0-alpha.81, 2026-05-23)
957
958- **From 3.7.0 onward we ship stable semver**, NOT alpha pre-releases.
959- Bump rules (semver discipline):
960 - **PATCH** (3.7.0 → 3.7.1): bug fixes only, no API change, no schema change
961 - **MINOR** (3.7.0 → 3.8.0): backward-compatible additions (new MCP tool, new flag, new agent type)
962 - **MAJOR** (3.x → 4.0.0): breaking change in CLI surface, MCP tool signature, file layout, or default behavior
963- Default tag is `latest` (no `--tag alpha`). The `alpha` and `v3alpha` dist-tags continue to exist for historical compatibility — point them at the same version as `latest`.
964- Never publish a pre-release (`-alpha.N`, `-beta.N`, `-rc.N`) unless the user explicitly asks for a pre-release flow.
965
966### Publishing Rules
967
968- The normal public release train is exactly THREE packages:
969 `@claude-flow/cli`, `claude-flow`, and `ruflo`.
970- Internal `@claude-flow/*` components are bundled into the public artifacts;
971 do not publish them standalone as part of the normal release.
972- MUST update ALL dist-tags for ALL THREE packages after publishing (latest + alpha + v3alpha all point to the same version)
973- Publish order: `@claude-flow/cli` first, then `claude-flow` (umbrella), then `ruflo` (alias umbrella)
974- MUST run verification for ALL THREE before telling user publishing is complete
975- Run `node scripts/audit-umbrella-version-lockstep.mjs` before packing or
976 publishing.
977- Publish from a clean reviewed commit/tag-equivalent worktree. Do not ship
978 unrelated uncommitted changes.
979- A fresh worktree has two separate dependency trees to install before anything
980 builds: `npm install` at repo root (npm workspaces), AND `pnpm install` inside
981 `v3/` (a separate pnpm workspace — root `prepare-root-publish.mjs` shells out to
982 `pnpm --filter` to build `v3/@claude-flow/{shared,hooks,guidance}`, which fails
983 with `spawn ENOENT` on `tsc` if `v3/node_modules` was never populated).
984- Use the existing authenticated `ruvnet` npm session. Do not replace it with a
985 token from another GCP project.
986
987**`npm publish` auth — FIXED (2026-07-30):** use the `NPM_TOKEN` secret directly,
988via a throwaway `.npmrc` with `NPM_CONFIG_USERCONFIG` — same pattern as the
989helpers-signing-key handling. It is mirrored in two GCP projects — `ruv-dev`
990(version 3+) and `cognitum-20260110` (version 7+) — so either project's copy
991is current; use whichever `gcloud` session is already authenticated. This is a
992granular access token ("ruflo publishjing", expires 2026-10-28) with
993`package: write` + `bypass_2fa: true`, scoped broadly enough to cover
994`@claude-flow/cli`, `claude-flow`, and `ruflo` (plus the `cognitum`/
995`cognitum-one` orgs). Confirmed end-to-end against the real registry (not just
996a permissions probe): `npm publish` for `@claude-flow/cli` succeeded via this
997token with zero OTP/WebAuthn prompt, and
998`npm dist-tag add` against both a scoped (`@claude-flow/cli`) and unscoped
999(`claude-flow`) package also went through with no prompt.
1000
1001**Why the earlier `NPM_TOKEN` version failed:** versions 1/2 of that secret
1002were older classic automation tokens, and npm has been restricting tokens that
1003bypass 2FA for writes account-wide (the login flow prints this notice —
1004`gh.io/npm-gat-bypass2fa-deprecation`). Version 3 is a **granular access
1005token** created explicitly for this purpose, which is npm's supported
1006replacement path (its own 2FA-bypass flag still works for a granular token,
1007unlike the deprecated classic automation tokens). If this token's `bypass_2fa`
1008flag or scope ever gets narrowed/expired (check expiry above), the fallback
1009is the WebAuthn dance below — but try this path first every time.
1010
1011```bash
1012gcloud secrets versions access latest --secret=NPM_TOKEN --project=ruv-dev > /tmp/.npmrc-publish-raw
1013printf '//registry.npmjs.org/:_authToken=%s\n' "$(cat /tmp/.npmrc-publish-raw)" > /tmp/.npmrc-publish
1014rm -f /tmp/.npmrc-publish-raw
1015NPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm publish # from the package dir, with signing-key env vars for @claude-flow/cli
1016NPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> alpha
1017NPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> v3alpha
1018shred -u /tmp/.npmrc-publish 2>/dev/null || rm -f /tmp/.npmrc-publish # ALWAYS clean up, same discipline as the signing key
1019```
1020
1021**Fallback — WebAuthn procedure, if the token above is dead:** the `ruvnet`
1022account's 2FA method is a WebAuthn security key, not TOTP (no numeric
1023`--otp=<code>` exists). This must be driven by the human (an agent cannot
1024approve a WebAuthn browser prompt):
10251. Human goes to npmjs.com → account 2FA settings → turns OFF "Require
1026 two-factor authentication for write actions" (narrows to auth-only, not a
1027 full 2FA disable), then runs `npm login` in their own terminal to refresh
1028 the session under the new setting.
10292. Agent can then run `npm publish` directly via Bash with no further prompt.
10303. **`npm dist-tag add` still requires a fresh WebAuthn approval PER CALL**
1031 regardless of the write-2FA setting — 6 individual browser approvals for a
1032 3-package release (alpha + v3alpha × 3), not 1. Tell the human up front.
1033- After every dist-tag call (or if unsure), verify with
1034 `npm view <pkg> dist-tags --json` — don't trust the CLI's own stdout alone, since
1035 a WebAuthn prompt that's still pending in the browser produces no terminal
1036 output an agent can see.
1037- Confirm the version actually landed (`npm view <pkg>@<version> version`) before
1038 telling the user publishing succeeded, same reasoning: a mid-publish approval
1039 that never gets answered fails silently from an agent's point of view.
1040
1041**Helpers signing key (required for `@claude-flow/cli` publish):** `npm publish`'s
1042`prepublishOnly` runs `scripts/sign-helpers.mjs`, which needs a private key to sign
1043`.claude/helpers/helpers.manifest.json`. The secret lives in GCP Secret Manager in the
1044**`ruv-dev`** project (not `cognitum-20260110` or `claude-flow` — checked both, not there),
1045secret name `ruflo-helpers-signing-key`:
1046
1047```bash
1048cd v3/@claude-flow/cli
1049RUFLO_HELPERS_SIGNING_SECRET=ruflo-helpers-signing-key RUFLO_HELPERS_SIGNING_PROJECT=ruv-dev \
1050 npm publish
1051```
1052
1053(`ruv-dev` also holds `ruflo-config-signing-key`; do not replace the existing
1054authenticated npm session with a token from another project.)
1055
1056**Handling the signing key without leaking it (learned 2026-07-14, hard way):**
1057an earlier Windows path invoked `gcloud` without its required `.cmd` suffix. The
1058fallback command printed the PEM into captured tool output and a session transcript.
1059GCP secret v1 was destroyed and a fresh v2 was rotated in (commit 0052b1b06 /
1060PR #2673). `sign-helpers.mjs` now selects `gcloud.cmd` on Windows and supports a
1061stdin-only fallback. **Rules:**
1062- NEVER invoke `gcloud secrets versions access` in a way that lets the payload reach
1063 tool output. Use the built-in `RUFLO_HELPERS_SIGNING_SECRET` path above, or pipe
1064 directly into the signer:
1065 `gcloud secrets versions access latest --secret=ruflo-helpers-signing-key --project=ruv-dev | node scripts/sign-helpers.mjs --stdin-key`.
1066- `--stdin-key` refuses interactive entry, validates Ed25519 key type, and never
1067 echoes parser input. A local file via `RUFLO_HELPERS_SIGNING_KEY` remains the
1068 air-gapped fallback.
1069- If a rotation IS needed, keep the private half in `~/.ruflo/helpers-signing.key`
1070 only, print ONLY the public half (via `Ed25519 pub export` from Node crypto), upload
1071 new private via `gcloud secrets versions add … --data-file=`, then
1072 `gcloud secrets versions destroy <old>` to make the old irrecoverable.
1073
1074**Windows `prepublishOnly` failure (learned 2026-07-14):** the CLI's `prepublishOnly`
1075chain (`cp ../../../README.md ./README.md && rm -rf plugins && mkdir -p plugins && cp -r ...`)
1076is POSIX-shell-only. On Windows, npm runs it via `cmd.exe /d /s /c` which chokes on
1077`mkdir -p` (interprets `-p` as a directory name) and `cp -r` (no such command). Two
1078workarounds until the script is rewritten in cross-platform Node:
10791. Run the prep steps manually in Git Bash, then `npm publish --ignore-scripts`.
10802. Or use a POSIX shell for the whole publish: `SHELL=bash npm publish` — but this
1081 doesn't always take effect on Windows depending on npm version.
1082Option 1 is what worked for v3.29.0. Track proper fix in ruvnet/ruflo issue for
1083cross-platform prepublish.
1084
1085**Concurrent-session helper corruption (real, observed, be paranoid):** multiple Claude Code
1086sessions can have their own `npm exec @claude-flow/cli@latest mcp start` MCP server running
1087concurrently with `cwd` inside this repo (check with `readlink /proc/<pid>/cwd` on
1088`pgrep -f "npm exec @claude-flow/cli@latest mcp start"`). If one of those resolved an older
1089cached `@latest` (predating the `semver.gte` downgrade-guard in
1090`helper-refresh.ts:autoRefreshHelpersIfStale`), it will silently overwrite this repo's
1091hand-maintained `.claude/helpers/hook-handler.cjs` / `intelligence.cjs` (root AND package
1092copies) — and `helpers.manifest.json` + `.helpers-version` — with its own older bundled
1093content, mid-session, with no warning. Observed live 2026-07-13: this happened *twice* in
1094one publish flow, once right after a manual revert and once right after signing (silently
1095invalidating a freshly-signed manifest). **Mitigation:** never trust the on-disk state of
1096those files between tool calls — `git diff --stat` them immediately before any `git add`/
1097`sign-helpers.mjs`/`npm publish` step, `git checkout HEAD --` revert if dirty, and chain
1098revert → sign → verify → add → commit as ONE bash invocation (`&&`-joined) to minimize the
1099race window. `npm publish`'s own `prepublishOnly` re-signs fresh at pack time regardless, so
1100what matters is the on-disk state at the *exact moment* `npm publish` runs, not before.
1101
1102```bash
1103# Replace 3.7.1 below with your chosen stable version (patch/minor/major per the rules above)
1104
1105# STEP 1: Build and publish @claude-flow/cli
1106cd v3/@claude-flow/cli
1107npm version 3.7.1 --no-git-tag-version
1108npm run build
1109npm publish # default tag is `latest` — no --tag flag
1110npm dist-tag add @claude-flow/cli@3.7.1 alpha # historical compat
1111npm dist-tag add @claude-flow/cli@3.7.1 v3alpha # historical compat
1112
1113# STEP 2: Publish claude-flow umbrella
1114cd /Users/cohen/Projects/ruflo # or your repo root
1115npm version 3.7.1 --no-git-tag-version
1116npm publish
1117npm dist-tag add claude-flow@3.7.1 alpha
1118npm dist-tag add claude-flow@3.7.1 v3alpha
1119
1120# STEP 3: Publish ruflo wrapper (CRITICAL — DON'T FORGET — this is what users run)
1121cd ruflo
1122npm version 3.7.1 --no-git-tag-version
1123npm publish
1124npm dist-tag add ruflo@3.7.1 alpha
1125npm dist-tag add ruflo@3.7.1 v3alpha
1126```
1127
1128**Verification (run before telling user publishing is complete):**
1129
1130```bash
1131for pkg in @claude-flow/cli claude-flow ruflo; do
1132 echo "$pkg: $(npm view $pkg@latest version)"
1133 npm view $pkg dist-tags --json
1134done
1135# All three must show latest === alpha === v3alpha === new version
1136```
1137
1138### All Tags That Must Be Updated
1139
1140| Package | Tag | Command Users Run |
1141|---------|-----|-------------------|
1142| `@claude-flow/cli` | `latest` | `npx @claude-flow/cli@latest` |
1143| `@claude-flow/cli` | `alpha` | `npx @claude-flow/cli@alpha` (legacy compat) |
1144| `@claude-flow/cli` | `v3alpha` | `npx @claude-flow/cli@v3alpha` (legacy compat) |
1145| `claude-flow` | `latest` | `npx claude-flow@latest` |
1146| `claude-flow` | `alpha` | `npx claude-flow@alpha` (legacy compat) |
1147| `claude-flow` | `v3alpha` | `npx claude-flow@v3alpha` (legacy compat) |
1148| `ruflo` | `latest` | `npx ruflo@latest` |
1149| `ruflo` | `alpha` | `npx ruflo@alpha` (legacy compat) |
1150| `ruflo` | `v3alpha` | `npx ruflo@v3alpha` (legacy compat) |
1151
1152- Never forget the `ruflo` package — it's the thin wrapper users actually run via `npx ruflo`
1153- The legacy `alpha` and `v3alpha` tags MUST stay pointed at the latest stable so old install commands keep working
1154- `ruflo` source is in `/ruflo/` — it depends on `@claude-flow/cli`
1155- Also remember to update `ruflo/package.json` overrides when adding new pinned transitives (see #2112 lesson — root overrides do NOT propagate to the published `ruflo` wrapper)
1156
1157### GitHub Release after publish
1158
1159Every stable bump SHOULD have a matching `gh release create v<version>` with consolidated release notes pointing at the gist if one exists. Example:
1160
1161```bash
1162git tag v3.7.1 main
1163git push origin v3.7.1
1164gh release create v3.7.1 --title "v3.7.1 — <one-line headline>" \
1165 --notes-file /tmp/release-notes.md
1166```
1167
1168## Plugin Registry Maintenance (IPFS/Pinata)
1169
1170The plugin registry is stored on IPFS via Pinata for decentralized, immutable distribution.
1171
1172### Registry Location
1173- **Current CID**: Stored in `v3/@claude-flow/cli/src/plugins/store/discovery.ts`
1174- **Gateway**: `https://gateway.pinata.cloud/ipfs/{CID}`
1175- **Format**: JSON with plugin metadata, categories, featured/trending lists
1176
1177### Required Environment Variables
1178Add to `.env` (NEVER commit actual values):
1179```bash
1180PINATA_API_KEY=your-api-key
1181PINATA_API_SECRET=your-api-secret
1182PINATA_API_JWT=your-jwt-token
1183```
1184
1185## Plugin Registry Operations
1186
1187### Adding a New Plugin to Registry
1188
11891. **Fetch current registry**:
1190```bash
1191curl -s "https://gateway.pinata.cloud/ipfs/$(grep LIVE_REGISTRY_CID v3/@claude-flow/cli/src/plugins/store/discovery.ts | cut -d"'" -f2)" > /tmp/registry.json
1192```
1193
11942. **Add plugin entry** to the `plugins` array:
1195```json
1196{
1197 "id": "@claude-flow/your-plugin",
1198 "name": "@claude-flow/your-plugin",
1199 "displayName": "Your Plugin",
1200 "description": "Plugin description",
1201 "version": "1.0.0-alpha.1",
1202 "size": 100000,
1203 "checksum": "sha256:abc123",
1204 "author": {"id": "claude-flow-team", "displayName": "Claude Flow Team", "verified": true},
1205 "license": "MIT",
1206 "categories": ["official"],
1207 "tags": ["your", "tags"],
1208 "downloads": 0,
1209 "rating": 5,
1210 "lastUpdated": "2026-01-25T00:00:00.000Z",
1211 "minClaudeFlowVersion": "3.0.0",
1212 "type": "integration",
1213 "hooks": [],
1214 "commands": [],
1215 "permissions": ["memory"],
1216 "exports": ["YourExport"],
1217 "verified": true,
1218 "trustLevel": "official"
1219}
1220```
1221
12223. **Update counts and arrays**:
1223 - Increment `totalPlugins`
1224 - Add to `official` array
1225 - Add to `featured`/`newest` if applicable
1226 - Update category `pluginCount`
1227
12284. **Upload to Pinata** (read credentials from .env):
1229```bash
1230# Source credentials from .env
1231PINATA_JWT=$(grep "^PINATA_API_JWT=" .env | cut -d'=' -f2-)
1232
1233# Upload updated registry
1234curl -X POST "https://api.pinata.cloud/pinning/pinJSONToIPFS" \
1235 -H "Authorization: Bearer $PINATA_JWT" \
1236 -H "Content-Type: application/json" \
1237 -d @/tmp/registry.json
1238```
1239
12405. **Update discovery.ts** with new CID:
1241```typescript
1242export const LIVE_REGISTRY_CID = 'NEW_CID_FROM_PINATA';
1243```
1244
12456. **Also update demo registry** in discovery.ts `demoPluginRegistry` for offline fallback
1246
1247### Security Rules
1248- NEVER hardcode API keys in scripts or source files
1249- NEVER commit .env (already in .gitignore)
1250- Always source credentials from environment at runtime
1251- Always delete temporary scripts after one-time uploads
1252
1253### Verification
1254```bash
1255# Verify new registry is accessible
1256curl -s "https://gateway.pinata.cloud/ipfs/{NEW_CID}" | jq '.totalPlugins'
1257```
1258
1259## MetaHarness Integration (ADR-150)
1260
1261Ruflo integrates with the upstream `metaharness` / `@metaharness/*` ecosystem as a sibling agent-harness scaffolding system (same author, designed around ruflo's primitives). MetaHarness packages are optional peer dependencies and are never required at runtime.
1262
1263### Architectural constraint (load-bearing)
1264
1265**Ruflo remains operational if every MetaHarness package is removed.** Four rules:
12661. **Removable**: `npm ls --without @metaharness/*` must still produce a working CLI
12672. **Optional in package.json**: `@metaharness/*` packages MUST be optional peers, never normal dependencies
12683. **Graceful degradation**: every code path that touches MetaHarness catches `MODULE_NOT_FOUND` and falls back
12694. **CI gate**: `.github/workflows/no-metaharness-smoke.yml` enforces all three by static grep + runtime drill on every PR
1270
1271### Command + tool surface
1272
1273```bash
1274# CLI subcommands (npx ruflo metaharness …)
1275npx ruflo metaharness score # 5-dim readiness scorecard
1276npx ruflo metaharness genome # 7-section categorical report
1277npx ruflo metaharness mcp-scan --fail-on high # static security findings
1278npx ruflo metaharness threat-model # enterprise threat report
1279npx ruflo metaharness oia-audit --alert-on-worst high
1280 # composite weekly audit → memory
1281npx ruflo metaharness audit-list --since 30d # enumerate audit records
1282npx ruflo metaharness audit-trend \ # diff two audits (drift)
1283 --baseline-key <a> --current-key <b> --alert-on-worsening \
1284 --alert-on-distance-below 0.85 # iter 38 — structural-distance gate (ADR-152 §3.1)
1285npx ruflo metaharness similarity \ # iter 36 — ADR-152 §3.1 weighted similarity
1286 --a a.json --b b.json [--per-dimension] [--alert-below 0.5]
1287npx ruflo metaharness drift-from-history \ # iter 53 — 1-command drift (composes 3 primitives)
1288 [--baseline-since 7d] [--baseline-key <key>] [--baseline-file <path>] \
1289 [--threshold 0.95] [--alert-on-new-severity high] [--dry-run]
1290 # iter 66 — --baseline-key skips audit-list (~14x faster)
1291 # iter 67 — --baseline-file skips memory entirely (~19x faster)
1292 # iter 78 — --alert-on-new-severity adds orthogonal finding-severity gate
1293npx ruflo metaharness mint --name foo --template vertical:coding --confirm
1294npx ruflo metaharness redblue init # @metaharness/redblue — scaffold redblue.yaml
1295npx ruflo metaharness redblue run --mock-judge --tests 10
1296 # $0 marker-fixture path (CI / offline)
1297npx ruflo metaharness redblue run --tests 50 --patch
1298 # real model judge (needs OPENROUTER_API_KEY,
1299 # capped by max_cost_usd, default $3)
1300npx ruflo metaharness redblue attack prompt --count 3
1301 # preview generated attack cases (no target call)
1302npx ruflo metaharness redblue patch --mock-judge # baseline → blue-team patch → retest delta
1303npx ruflo metaharness redblue report --in report.json
1304 # render existing report as markdown
1305npx ruflo metaharness learn --host claude-code --model haiku --slice slices/lite.json
1306 # metaharness@0.3.0 / upstream ADR-235 —
1307 # GEPA learning run; $0 dry-run default,
1308 # --run to spend; needs a metaharness
1309 # repo checkout (--repo / $METAHARNESS_REPO)
1310npx ruflo metaharness gepa --op genome # darwin@0.8.0 GEPA library — load + validate
1311 # the shipped cand-6 genome (or --path <f>)
1312npx ruflo metaharness gepa --op render # genome → the system prompt it compiles to
1313npx ruflo metaharness gepa --op analyze --transcript run.json
1314 # classify failure modes in a transcript
1315npx ruflo metaharness evolve --bench .harness/bench.json
1316 # Darwin proposes candidates; governed gates decide
1317npx ruflo metaharness bench verify --path .harness/bench.json
1318 # create or verify stable benchmark corpora
1319npx ruflo metaharness flywheel run --proposer auto --max-concurrency 2
1320 # bounded concurrent evaluation; does not promote
1321npx ruflo metaharness flywheel receipts # inspect immutable evaluation receipts
1322npx ruflo metaharness flywheel promote <receipt-id> \
1323 --public-key ./approved-ed25519-public.pem --confirm
1324 # explicit policy-authorized atomic promotion
1325
1326# Dedicated command
1327npx ruflo eject --name my-harness # lift ruflo project → standalone harness
1328 # dry-run by default; refuses in-repo target
1329
1330# Doctor health check
1331npx ruflo doctor --component metaharness # report metaharness availability + version
1332
1333# MCP tools (callable by Claude Code agents)
1334mcp__claude-flow__metaharness_score
1335mcp__claude-flow__metaharness_genome
1336mcp__claude-flow__metaharness_mcp_scan
1337mcp__claude-flow__metaharness_threat_model
1338mcp__claude-flow__metaharness_oia_audit
1339mcp__claude-flow__metaharness_audit_list
1340mcp__claude-flow__metaharness_audit_trend
1341mcp__claude-flow__metaharness_similarity # iter 36 — ADR-152 §3.1 genome similarity
1342mcp__claude-flow__metaharness_drift_from_history # iter 53 — 1-command drift detection
1343mcp__claude-flow__metaharness_bench # ADR-153 — create/verify bench suites for evolve --bench
1344mcp__claude-flow__metaharness_evolve # MAP-Elites driver — evolve a harness across bench suites
1345mcp__claude-flow__metaharness_security_bench # security-focused benchmark suite gate
1346mcp__claude-flow__metaharness_redblue # @metaharness/redblue — adversarial red/blue LLM testing (init|run|patch|attack|report)
1347mcp__claude-flow__metaharness_learn # metaharness@0.3.0 — GEPA learning run ($0 dry-run default; run=true to spend)
1348mcp__claude-flow__metaharness_gepa # darwin@0.8.0 — GEPA genome ops (genome|validate|render|analyze); gepaOptimize stays library-only
1349mcp__claude-flow__metaharness_flywheel # ADR-322 — evaluate concurrently, inspect receipts/ledger, or explicitly promote
1350```
1351
1352### Routing integration (ADR-148/149)
1353
1354`@metaharness/router@~0.3.2` is wired as the cost-optimal model router behind the `CLAUDE_FLOW_ROUTER_NEURAL=1` triple-gate. The `routedBy` field on every routing decision carries `'metaharness-knn' | 'metaharness-krr' | 'fastgrnn'` when the neural path is active.
1355
1356### SelfEvolvingRouter parallel-logging (ADR-150 Phase 2)
1357
1358When `CLAUDE_FLOW_ROUTER_PARALLEL_LOG=1` is set, every `route()` call writes a paired-decision row (bandit pick + neural-augmented pick + outcome) to `.swarm/router-parallel.jsonl`. Analyze with:
1359
1360```bash
1361node plugins/ruflo-metaharness/scripts/router-parallel-analyze.mjs \
1362 --input .swarm/router-parallel.jsonl --strict
1363```
1364
1365The 3-criteria AND-gate from ADR-150 review-round-1: `quality > 2% AND cost < 1% AND latency < 5%`. Exit 1 in `--strict` mode if any criterion fails — promotion gate.
1366
1367### CI workflows
1368
1369- `metaharness-ci.yml` — score / mcp-scan / router-compat / eject-dryrun jobs on every PR touching `plugins/ruflo-metaharness/**`
1370- `no-metaharness-smoke.yml` — enforces the four architectural-constraint rules above on every PR
1371- `oia-audit-weekly.yml` — Sundays 04:17 UTC, runs composite audit, uploads 90-day artifact
1372
1373### Cross-references
1374
1375- [ADR-150](v3/docs/adr/ADR-150-metaharness-integration-surfaces.md) — decision + implementation notes
1376- [Issue #2399](https://github.com/ruvnet/ruflo/issues/2399) — phase tracker
1377- [Research gist](https://gist.github.com/ruvnet/19d166ff9acf368c9da4172d91ac9113) — graded evidence
1378- Upstream: `github.com/ruvnet/agent-harness-generator`
1379
1380## Optional Plugins (20 Available)
1381
1382Plugins are distributed via IPFS and can be installed with the CLI. Browse and install from the official registry:
1383
1384```bash
1385# List all available plugins
1386npx claude-flow@v3alpha plugins list
1387
1388# Install a plugin
1389npx claude-flow@v3alpha plugins install @claude-flow/plugin-name
1390
1391# Enable/disable
1392npx claude-flow@v3alpha plugins enable @claude-flow/plugin-name
1393npx claude-flow@v3alpha plugins disable @claude-flow/plugin-name
1394```
1395
1396### Core Plugins
1397
1398| Plugin | Version | Description |
1399|--------|---------|-------------|
1400| `@claude-flow/embeddings` | 3.0.0-alpha.1 | Vector embeddings with sql.js, HNSW, hyperbolic support |
1401| `@claude-flow/security` | 3.0.0-alpha.1 | Input validation, path security, CVE remediation |
1402| `@claude-flow/claims` | 3.0.0-alpha.8 | Claims-based authorization (check, grant, revoke, list) |
1403| `@claude-flow/neural` | 3.0.0-alpha.7 | Neural pattern training (SONA, MoE, EWC++) |
1404| `@claude-flow/plugins` | 3.0.0-alpha.1 | Plugin system core (manager, discovery, store) |
1405| `@claude-flow/performance` | 3.0.0-alpha.1 | Performance profiling and benchmarking |
1406
1407### Integration Plugins
1408
1409| Plugin | Version | Description |
1410|--------|---------|-------------|
1411| `@claude-flow/plugin-agentic-qe` | 3.0.0-alpha.4 | Agentic quality engineering integration |
1412| `@claude-flow/plugin-prime-radiant` | 0.1.5 | Prime Radiant intelligence integration |
1413| `@claude-flow/plugin-gastown-bridge` | 3.0.0-alpha.1 | Gastown bridge protocol integration |
1414| `@claude-flow/teammate-plugin` | 1.0.0-alpha.1 | Multi-agent teammate coordination |
1415| `@claude-flow/plugin-code-intelligence` | 0.1.0 | Advanced code analysis and intelligence |
1416| `@claude-flow/plugin-test-intelligence` | 0.1.0 | Intelligent test generation and gap analysis |
1417| `@claude-flow/plugin-perf-optimizer` | 0.1.0 | Performance optimization automation |
1418| `@claude-flow/plugin-neural-coordinator` | 0.1.0 | Neural network coordination across agents |
1419| `@claude-flow/plugin-cognitive-kernel` | 0.1.0 | Core cognitive processing kernel |
1420| `@claude-flow/plugin-quantum-optimizer` | 0.1.0 | Quantum-inspired optimization algorithms |
1421| `@claude-flow/plugin-hyperbolic-reasoning` | 0.1.0 | Hyperbolic space reasoning for hierarchical data |
1422
1423### Domain-Specific Plugins
1424
1425| Plugin | Version | Description |
1426|--------|---------|-------------|
1427| `@claude-flow/plugin-healthcare-clinical` | 0.1.0 | Healthcare clinical workflow automation |
1428| `@claude-flow/plugin-financial-risk` | 0.1.0 | Financial risk assessment and modeling |
1429| `@claude-flow/plugin-legal-contracts` | 0.1.0 | Legal contract analysis and generation |
1430
1431### Plugin Development
1432
1433```bash
1434# Create a new plugin from template
1435npx claude-flow@v3alpha plugins create my-plugin
1436
1437# Test locally
1438npx claude-flow@v3alpha plugins install ./path/to/my-plugin
1439
1440# Publish to registry (requires Pinata credentials)
1441npx claude-flow@v3alpha plugins publish
1442```
1443
1444Registry source: IPFS via Pinata (`QmXbfEAaR7D2Ujm4GAkbwcGZQMHqAMpwDoje4583uNP834`)
1445
1446## Support
1447
1448- Documentation: https://github.com/ruvnet/claude-flow
1449- Issues: https://github.com/ruvnet/claude-flow/issues
1450
1451---
1452
1453Remember: **Claude Flow coordinates, Claude Code creates!**
1454
1455## Gateway-Delegated Development (meta-llm dev-bridge)
1456
1457For complex reasoning, architecture decisions, or hard bug-fixes, **delegate via the
1458`metallm_delegate` MCP tool rather than solving inline.** The meta-llm gateway governs the
1459work: it routes cheap-tier-first, escalates genuinely-hard tasks to the frontier (Fable),
1460and meters every call — so delegation is cost-governed and preserves the main session's context.
1461
1462- **Default to `cognitum-auto`** — the gateway picks the tier by difficulty. Only pass an
1463 explicit tier (`cognitum-low|mid|high`) when you must force one.
1464- Prompt-wrapping does **not** inflate cost — the gateway normalizes host scaffolds so an
1465 everyday sub-task still routes to the cheap tier. Trust `cognitum-auto`.
1466- Use **`metallm_delegate`** for agentic sub-tasks needing tools/files in a working dir
1467 (its `cwd` is sandboxed); use **`metallm_ask`** for a single-shot question — it returns
1468 the gateway's real metered cost + resolved tier/model in-band.
1469- Reserve the main (inline) session for orchestration, integration, and final review;
1470 push expensive per-sub-task reasoning through the gateway.
1471
1472**Setup (per developer, local — never committed):** register the `metallm-dev-bridge` MCP
1473server via a local `.mcp.json` (gitignored) and export your gateway key as `COGNITUM_DEV_KEY`
1474in your shell. Build steps + the exact `.mcp.json` block are in the internal meta-llm
1475dev-bridge README. **Never commit the key or an inline gateway URL.**
1476
1477### `ask` vs `delegate` — pick by task shape (load-bearing)
1478
1479**Use `metallm_ask` for single-shot facts, summaries, classification, and small code
1480questions. Use `metallm_delegate` only when the task needs autonomous multi-step execution
1481or isolated agent context.**
1482
1483Why the split is strict: `metallm_delegate` spawns a full `claude -p` sub-agent, which loads
1484its entire harness context **even for a trivial task** — measured floor ≈ **$0.26/call**
1485(~43k input tokens) before any real work. `metallm_ask` is a single gateway completion —
1486measured ≈ **$0.0001** for a small query, ~2500× cheaper. So delegating casually is
1487expensive at volume; `delegate` pays off only when offloading the sub-task's context from
1488the main session is worth the floor. When in doubt, `ask`.
1489
1490Routing caveat (tracked): `metallm_ask` **auto** currently over-tiers some trivial prompts to
1491`mid` (sonnet-5) instead of `low` — the bridge's `/v1/messages` path may miss ADR-236
1492host-normalization (meta-llm issue #38). Forced tiers work correctly; cost impact is small
1493per call but real at volume.
1494
@@ −1 +1 @@
1−# CLAUDE.md
1+# Claude Code Configuration - Ruflo V3
22
3−This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
3+> Public release train: `@claude-flow/cli`, `claude-flow`, and `ruflo`.
4+> Use package manifests and the registry as version truth; do not copy stale
5+> version or capability counts into agent guidance.
46
5−## Overview
7+## Behavioral Rules (Always Enforced)
68
7−Chat UI is a SvelteKit application that provides a chat interface for LLMs. It powers HuggingChat (hf.co/chat). The app speaks exclusively to OpenAI-compatible APIs via `OPENAI_BASE_URL`.
9+- Do what has been asked; nothing more, nothing less
10+- NEVER create files unless they're absolutely necessary for achieving your goal
11+- ALWAYS prefer editing an existing file to creating a new one
12+- NEVER proactively create documentation files (*.md) or README files unless explicitly requested
13+- NEVER save working files, text/mds, or tests to the root folder
14+- Never continuously check status after spawning a swarm — wait for results
15+- ALWAYS read a file before editing it
16+- NEVER commit secrets, credentials, or .env files
817
9−## Commands
18+## Capability Brain and Governed Implementation
1019
20+Ruflo is the coordination ledger and policy decision point. Claude Code
21+executes code, tests, commands, and file changes. A Ruflo coordination call
22+records work; it does not perform the implementation.
23+
24+When registered, call
25+`guidance_brain({ mode: "recommend", task: "..." })` before complex Ruflo
26+work. Use its live registry rather than guessing tool names. Treat
27+`registered`, `configured`, `reachable`, `healthy`, and `authorized` as
28+separate facts. If unavailable, continue with compatible guidance tools, CLI
29+discovery, and these repository instructions.
30+
31+Use this loop: recall → inspect → route → plan → execute → test → validate →
32+benchmark → optimize → receipt → handoff → separately authorized publish.
33+
34+## File Organization
35+
36+- NEVER save to root folder — use the directories below
37+- Use `/src` for source code files
38+- Use `/tests` for test files
39+- Use `/docs` for documentation and markdown files
40+- Use `/config` for configuration files
41+- Use `/scripts` for utility scripts
42+- Use `/examples` for example code
43+
44+## Project Architecture
45+
46+- Follow Domain-Driven Design with bounded contexts
47+- Keep files under 500 lines
48+- Use typed interfaces for all public APIs
49+- Prefer TDD London School (mock-first) for new code
50+- Use event sourcing for state changes
51+- Ensure input validation at system boundaries
52+
53+### Key Packages
54+
55+| Package | Path | Purpose |
56+|---------|------|---------|
57+| `@claude-flow/cli` | `v3/@claude-flow/cli/` | CLI entry point (26 commands) |
58+| `@claude-flow/codex` | `v3/@claude-flow/codex/` | Dual-mode Claude + Codex collaboration |
59+| `@claude-flow/guidance` | `v3/@claude-flow/guidance/` | Governance control plane |
60+| `@claude-flow/hooks` | `v3/@claude-flow/hooks/` | 17 hooks + 12 workers |
61+| `@claude-flow/memory` | `v3/@claude-flow/memory/` | AgentDB + HNSW search |
62+| `@claude-flow/security` | `v3/@claude-flow/security/` | Input validation, CVE remediation |
63+
64+## Concurrent Automated Development
65+
66+- Parallelize independent research, tests, reviews, and non-overlapping
67+ implementation.
68+- Never allow two writers in one worktree. Give every writing agent an isolated
69+ worktree and explicit file ownership.
70+- Read-only agents may share a checkout; writing agents may not.
71+- Only the integration owner edits shared manifests and lockfiles or reconciles
72+ overlapping changes.
73+- Continue independent local work after spawning agents; wait only when a real
74+ dependency blocks progress. Do not repeatedly poll.
75+- A lease or work claim coordinates ownership; it never grants authority.
76+- Bind tests, benchmarks, policy decisions, and handoffs to an exact clean
77+ commit or immutable dirty-worktree snapshot.
78+- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose and
79+ evaluate candidates, but cannot self-promote or expand tools, network,
80+ secrets, spend, concurrency, or release authority.
81+
82+---
83+
84+## Swarm Orchestration
85+
86+- MUST initialize the swarm using MCP tools when starting complex tasks
87+- MUST spawn concurrent agents using Claude Code's Task tool
88+- Never use MCP tools alone for execution — Task tool agents do the actual work
89+
90+### MCP + Task Tool in SAME Message
91+
92+- MUST call MCP tools AND Task tool in ONE message for complex work
93+- Always call MCP first, then IMMEDIATELY call Task tool to spawn agents
94+
95+### 3-Tier Model Routing (ADR-026, ADR-143)
96+
97+| Tier | Handler | Latency | Cost | Use Cases |
98+|------|---------|---------|------|-----------|
99+| **1** | Deterministic codemod | ~1ms | $0 | Structural transforms with **no LLM**: `var-to-const`, `remove-console`, `add-logging` |
100+| **2** | Haiku | ~500ms | $0.0002 | Simple tasks, low complexity (<30%) |
101+| **3** | Sonnet/Opus | 2-5s | $0.003-0.015 | Complex reasoning, architecture, security (>30%) |
102+
103+- Always check for `[CODEMOD_AVAILABLE]` or `[TASK_MODEL_RECOMMENDATION]` before spawning agents
104+- When you see `[CODEMOD_AVAILABLE]`, call the `hooks_codemod` MCP tool (intent + file) — it applies the transform deterministically via the TypeScript compiler at $0, no LLM. Deterministic intents only: `var-to-const`, `remove-console`, `add-logging`
105+- `add-types`, `add-error-handling`, `async-await` need judgement and route to a model (Tier 2/3) — they are **not** $0 codemods (see ADR-143)
106+- Agent Booster (`agent-booster`) is a fast-apply merge engine for arbitrary LLM-produced edit snippets, not an intent-transform engine — it is **not** the Tier-1 path
107+
108+## Swarm Configuration & Anti-Drift
109+
110+### Anti-Drift Coding Swarm (PREFERRED DEFAULT)
111+
112+- ALWAYS use hierarchical topology for coding swarms
113+- Keep maxAgents at 6-8 for tight coordination
114+- Use specialized strategy for clear role boundaries
115+- Use `raft` consensus for hive-mind (leader maintains authoritative state)
116+- Run frequent checkpoints via `post-task` hooks
117+- Keep shared memory namespace for all agents
118+- Keep task cycles short with verification gates
119+
120+```javascript
121+mcp__ruv-swarm__swarm_init({
122+ topology: "hierarchical",
123+ maxAgents: 8,
124+ strategy: "specialized"
125+})
126+```
127+
128+## Dual-Mode Collaboration (Claude Code + Codex)
129+
130+This 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.
131+
132+### Why Dual-Mode?
133+
134+| Single Platform | Dual-Mode Collaboration |
135+|----------------|------------------------|
136+| One model's perspective | Two AI platforms cross-validating |
137+| Limited reasoning styles | Complementary strengths |
138+| No external verification | Built-in code review |
139+| Sequential workflows | Parallel execution |
140+
141+### Dual-Mode Swarm Protocol
142+
143+For complex tasks, spawn both Claude and Codex workers in parallel:
144+
145+```javascript
146+// STEP 1: Initialize dual-mode swarm
147+mcp__ruv-swarm__swarm_init({
148+ topology: "hierarchical",
149+ maxAgents: 8,
150+ strategy: "specialized"
151+})
152+
153+// STEP 2: Spawn BOTH platforms in parallel via Task tool
154+// 🔵 Claude Code workers (architecture, security, testing)
155+Task("Architect", "Design the implementation. Store design in memory namespace 'collaboration'.", "system-architect")
156+Task("Tester", "Write tests based on architect's design. Read from 'collaboration' namespace.", "tester")
157+Task("Reviewer", "Review code quality and security. Store findings in 'collaboration'.", "reviewer")
158+
159+// 🟢 Codex workers (implementation, optimization)
160+// Spawn via CLI for Codex platform
161+Bash("npx claude-flow-codex dual run --worker 'codex:coder:Implement the solution based on architect design' --namespace collaboration")
162+Bash("npx claude-flow-codex dual run --worker 'codex:optimizer:Optimize performance based on implementation' --namespace collaboration")
163+
164+// STEP 3: Coordinate via shared memory
165+Bash("npx claude-flow@v3alpha memory store --namespace collaboration --key 'task-context' --value '[task description]'")
166+```
167+
168+### Collaboration Templates (Pre-Built Pipelines)
169+
170+| Template | Workers | Pipeline |
171+|----------|---------|----------|
172+| `feature` | 🔵 Architect → 🟢 Coder → 🔵 Tester → 🟢 Reviewer | Full feature development |
173+| `security` | 🔵 Analyst → 🟢 Scanner → 🔵 Reporter | Security audit workflow |
174+| `refactor` | 🔵 Architect → 🟢 Refactorer → 🔵 Tester | Code modernization |
175+| `bugfix` | 🔵 Researcher → 🟢 Coder → 🔵 Tester | Bug investigation & fix |
176+
177+### Dual-Mode CLI Commands
178+
11179 ```bash
12−npm run dev # Start dev server on localhost:5173
13−npm run build # Production build
14−npm run preview # Preview production build
15−npm run check # TypeScript validation (svelte-kit sync + svelte-check)
16−npm run lint # Check formatting (Prettier) and linting (ESLint)
17−npm run format # Auto-format with Prettier
18−npm run test # Run all tests (Vitest)
180+# Run a collaboration template
181+npx claude-flow-codex dual run feature --task "Add user authentication with OAuth"
182+npx claude-flow-codex dual run security --target "./src"
183+npx claude-flow-codex dual run refactor --target "./src/legacy"
184+
185+# Custom multi-platform swarm
186+npx claude-flow-codex dual run \
187+ --worker "claude:architect:Design the API structure" \
188+ --worker "codex:coder:Implement REST endpoints" \
189+ --worker "claude:tester:Write integration tests" \
190+ --worker "codex:reviewer:Review code quality" \
191+ --namespace "api-feature"
192+
193+# Check collaboration status
194+npx claude-flow-codex dual status
195+
196+# List available templates
197+npx claude-flow-codex dual templates
19198 ```
20199
21−### Running a Single Test
200+### Shared Memory Coordination
22201
202+All workers share state via the `collaboration` namespace:
203+
23204 ```bash
24−npx vitest run path/to/file.spec.ts # Run specific test file
25−npx vitest run -t "test name" # Run test by name
26−npx vitest --watch path/to/file.spec.ts # Watch mode for single file
205+# Store context for cross-platform sharing
206+npx claude-flow@v3alpha memory store --namespace collaboration --key "design-decisions" --value "..."
207+
208+# Search for patterns across all workers
209+npx claude-flow@v3alpha memory search --namespace collaboration --query "authentication patterns"
210+
211+# Retrieve specific findings
212+npx claude-flow@v3alpha memory retrieve --namespace collaboration --key "security-findings"
27213 ```
28214
29−### Test Environments
215+### Cross-Platform Learning
30216
31−Tests are split into three workspaces (configured in vite.config.ts):
217+Both platforms learn from each other's outputs:
32218
33−- **Client tests** (`*.svelte.test.ts`): Browser environment with Playwright
34−- **SSR tests** (`*.ssr.test.ts`): Node environment for server-side rendering
35−- **Server tests** (`*.test.ts`, `*.spec.ts`): Node environment for utilities
219+```bash
220+# After successful collaboration, train patterns
221+npx claude-flow@v3alpha hooks post-task --task-id "dual-[id]" --success true --train-neural true
36222
37−## Architecture
223+# Store successful collaboration patterns
224+npx claude-flow@v3alpha memory store --namespace patterns --key "dual-mode-[pattern]" --value "[what worked]"
38225
39−### Stack
226+# Transfer learnings to both platforms
227+npx claude-flow@v3alpha hooks transfer store --pattern "dual-collab-success"
228+```
40229
41−- **SvelteKit 2** with Svelte 5 (uses runes: `$state`, `$effect`, `$bindable`)
42−- **MongoDB** for persistence (auto-fallback to in-memory with MongoMemoryServer when `MONGODB_URL` not set)
43−- **TailwindCSS** for styling
230+### Worker Dependency Levels
44231
45−### Key Directories
232+Workers execute in dependency order:
46233
47234 ```
48−src/
49−├── lib/
50−│ ├── components/ # Svelte components (chat/, mcp/, voice/, icons/)
51−│ ├── server/
52−│ │ ├── api/utils/ # Shared API helpers (auth, superjson, model/conversation resolvers)
53−│ │ ├── textGeneration/ # LLM streaming pipeline
54−│ │ ├── mcp/ # Model Context Protocol integration
55−│ │ ├── router/ # Smart model routing (Omni)
56−│ │ ├── database.ts # MongoDB collections
57−│ │ ├── models.ts # Model registry from OPENAI_BASE_URL/models
58−│ │ └── auth.ts # OpenID Connect authentication
59−│ ├── types/ # TypeScript interfaces (Conversation, Message, User, Model, etc.)
60−│ ├── stores/ # Svelte stores for reactive state
61−│ └── utils/ # Helpers (tree/, marked.ts, auth.ts, etc.)
62−├── routes/ # SvelteKit file-based routing
63−│ ├── conversation/[id]/ # Chat page + streaming endpoint
64−│ ├── settings/ # User settings pages
65−│ ├── api/ # Legacy v1 API endpoints (mcp, transcribe, fetch-url)
66−│ ├── api/v2/ # REST API endpoints (+server.ts)
67−│ └── r/[id]/ # Shared conversation view
235+Level 0: [🔵 Architect] # No dependencies - runs first
236+Level 1: [🟢 Coder, 🔵 Tester] # Depends on Architect
237+Level 2: [🔵 Reviewer] # Depends on Coder + Tester
238+Level 3: [🟢 Optimizer] # Depends on Reviewer approval
68239 ```
69240
70−### Text Generation Flow
241+### Platform Strengths
71242
72−1. User sends message via `POST /conversation/[id]`
73−2. Server validates user, fetches conversation history
74−3. Builds message tree structure (see `src/lib/utils/tree/`)
75−4. Calls LLM endpoint via OpenAI client
76−5. Streams response back, stores in MongoDB
243+| Task Type | Preferred Platform | Reason |
244+|-----------|-------------------|--------|
245+| Architecture & Design | 🔵 Claude | Strong reasoning, system thinking |
246+| Implementation | 🟢 Codex | Fast code generation |
247+| Security Review | 🔵 Claude | Careful analysis, threat modeling |
248+| Performance Optimization | 🟢 Codex | Code-level optimizations |
249+| Testing Strategy | 🔵 Claude | Coverage analysis, edge cases |
250+| Refactoring | 🟢 Codex | Bulk code transformations |
77251
78−### Model Context Protocol (MCP)
252+### Programmatic API
79253
80−MCP servers are configured via `MCP_SERVERS` env var. When enabled, tools are exposed as OpenAI function calls. The router can auto-select tools-capable models when `LLM_ROUTER_ENABLE_TOOLS=true`.
254+```typescript
255+import { DualModeOrchestrator, CollaborationTemplates } from '@claude-flow/codex';
81256
82−### LLM Router (Omni)
257+const orchestrator = new DualModeOrchestrator({
258+ namespace: 'my-feature',
259+ memoryBackend: 'hybrid'
260+});
83261
84−Smart routing via Arch-Router model. Configured with:
262+// Use pre-built template
263+const workers = CollaborationTemplates.featureDevelopment('Add OAuth login');
85264
86−- `LLM_ROUTER_ROUTES_PATH`: JSON file defining routes
87−- `LLM_ROUTER_ARCH_BASE_URL`: Router endpoint
88−- Shortcuts: multimodal routes bypass router if `LLM_ROUTER_ENABLE_MULTIMODAL=true`
265+// Run collaboration
266+const results = await orchestrator.runCollaboration(workers, 'Implement OAuth feature');
89267
90−### Database Collections
268+// Access shared memory
269+const designDocs = await orchestrator.getMemory('design-decisions');
270+```
91271
92−- `conversations` - Chat sessions with nested messages
93−- `users` - User accounts (OIDC-backed)
94−- `sessions` - Session data
95−- `sharedConversations` - Public share links
96−- `settings` - User preferences
272+---
97273
98−## Environment Setup
274+## Swarm Protocols & Routing
99275
100−Copy `.env` to `.env.local` and configure:
276+### Auto-Start Swarm Protocol
101277
102−```env
103−OPENAI_BASE_URL=https://router.huggingface.co/v1
104−OPENAI_API_KEY=hf_***
105−# MONGODB_URL is optional; omit for in-memory DB persisted to ./db
278+When the user requests a complex task (multi-file changes, feature implementation, refactoring), **immediately execute this pattern in a SINGLE message:**
279+
280+```javascript
281+// STEP 1: Initialize swarm coordination via MCP
282+mcp__ruv-swarm__swarm_init({
283+ topology: "hierarchical",
284+ maxAgents: 8,
285+ strategy: "specialized"
286+})
287+
288+// STEP 2: Spawn NAMED agents concurrently — all in ONE message
289+// Each agent knows WHO to message next in the pipeline
290+Task({
291+ prompt: "Research requirements and codebase. SendMessage findings to 'architect' when done.",
292+ subagent_type: "researcher", name: "researcher", run_in_background: true
293+})
294+Task({
295+ prompt: "Wait for research from 'researcher'. Design implementation. SendMessage design to 'coder'.",
296+ subagent_type: "system-architect", name: "architect", run_in_background: true
297+})
298+Task({
299+ prompt: "Wait for design from 'architect'. Implement the solution. SendMessage code paths to 'tester'.",
300+ subagent_type: "coder", name: "coder", run_in_background: true
301+})
302+Task({
303+ prompt: "Wait for implementation from 'coder'. Write tests. SendMessage results to 'reviewer'.",
304+ subagent_type: "tester", name: "tester", run_in_background: true
305+})
306+Task({
307+ prompt: "Wait for test results from 'tester'. Review code quality and security. Report findings.",
308+ subagent_type: "reviewer", name: "reviewer", run_in_background: true
309+})
310+
311+// STEP 3: Kick off the pipeline
312+SendMessage({ to: "researcher", summary: "Start research", message: "[task description and context]" })
313+
314+// STEP 4: Batch todos
315+TodoWrite({ todos: [
316+ {content: "Research and analyze requirements", status: "in_progress", activeForm: "Researching"},
317+ {content: "Design architecture", status: "pending", activeForm: "Designing"},
318+ {content: "Implement solution", status: "pending", activeForm: "Implementing"},
319+ {content: "Write tests", status: "pending", activeForm: "Testing"},
320+ {content: "Review and finalize", status: "pending", activeForm: "Reviewing"}
321+]})
322+
323+// Pipeline flow via SendMessage:
324+// researcher ──→ architect ──→ coder ──→ tester ──→ reviewer
106325 ```
107326
108−See `.env` for full list of variables including router config, MCP servers, auth, and feature flags.
327+### Agent Routing (Anti-Drift)
109328
110−## Code Conventions
329+| Code | Task | Agents |
330+|------|------|--------|
331+| 1 | Bug Fix | coordinator, researcher, coder, tester |
332+| 3 | Feature | coordinator, architect, coder, tester, reviewer |
333+| 5 | Refactor | coordinator, architect, coder, reviewer |
334+| 7 | Performance | coordinator, perf-engineer, coder |
335+| 9 | Security | coordinator, security-architect, auditor |
336+| 11 | Memory | coordinator, memory-specialist, perf-engineer |
337+| 13 | Docs | researcher, api-docs |
111338
112−- TypeScript strict mode enabled
113−- ESLint: no `any`, no non-null assertions
114−- Prettier: tabs, 100 char width, Tailwind class sorting
115−- Server vs client separation via SvelteKit conventions (`+page.server.ts` vs `+page.ts`)
339+**Codes 1-11: hierarchical/specialized (anti-drift). Code 13: mesh/balanced**
116340
117−## Feature Development Checklist
341+### Task Complexity Detection
118342
119−When building new features, consider:
343+**AUTO-INVOKE SWARM when task involves:**
344+- Multiple files (3+)
345+- New feature implementation
346+- Refactoring across modules
347+- API changes with tests
348+- Security-related changes
349+- Performance optimization
350+- Database schema changes
120351
121−1. **HuggingChat vs self-hosted**: Wrap HuggingChat-specific features with `publicConfig.isHuggingChat`
122−2. **Settings persistence**: Add new fields to `src/lib/types/Settings.ts`, update API endpoint at `src/routes/api/v2/user/settings/+server.ts`
123−3. **Rich dropdowns**: Use `bits-ui` (Select, DropdownMenu) instead of native elements when you need icons/images in options
124−4. **Scrollbars**: Use `scrollbar-custom` class for styled scrollbars
125−5. **Icons**: Custom icons in `$lib/components/icons/`, use Carbon (`~icons/carbon/*`) or Lucide (`~icons/lucide/*`) for standard icons
126−6. **Provider avatars**: Use `PROVIDERS_HUB_ORGS` from `@huggingface/inference` for HF provider avatar URLs
352+**SKIP SWARM for:**
353+- Single file edits
354+- Simple bug fixes (1-2 lines)
355+- Documentation updates
356+- Configuration changes
357+- Quick questions/exploration
358+
359+## Project Configuration
360+
361+This project is configured with Claude Flow V3 (Anti-Drift Defaults):
362+- **Topology**: hierarchical (prevents drift via central coordination)
363+- **Max Agents**: 8 (smaller team = less drift)
364+- **Strategy**: specialized (clear roles, no overlap)
365+- **Consensus**: raft (leader maintains authoritative state)
366+- **Memory Backend**: hybrid (SQLite + AgentDB)
367+- **HNSW Indexing**: Enabled (measured ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force; ANN wins above the crossover)
368+- **Neural Learning**: Enabled (SONA)
369+
370+## V3 CLI Commands (26 Commands, 140+ Subcommands)
371+
372+### Core Commands
373+
374+| Command | Subcommands | Description |
375+|---------|-------------|-------------|
376+| `init` | 4 | Project initialization with wizard, presets, skills, hooks |
377+| `agent` | 8 | Agent lifecycle (spawn, list, status, stop, metrics, pool, health, logs) |
378+| `swarm` | 6 | Multi-agent swarm coordination and orchestration |
379+| `memory` | 11 | AgentDB memory with HNSW vector search (measured ~1.9x–4.7x vs brute force above crossover) |
380+| `mcp` | 9 | MCP server management and tool execution |
381+| `task` | 6 | Task creation, assignment, and lifecycle |
382+| `session` | 7 | Session state management and persistence |
383+| `config` | 7 | Configuration management and provider setup |
384+| `status` | 3 | System status monitoring with watch mode |
385+| `start` | 3 | Service startup and quick launch |
386+| `workflow` | 6 | Workflow execution and template management |
387+| `hooks` | 17 | Self-learning hooks + 12 background workers |
388+| `hive-mind` | 6 | Queen-led Byzantine fault-tolerant consensus |
389+
390+### Advanced Commands
391+
392+| Command | Subcommands | Description |
393+|---------|-------------|-------------|
394+| `daemon` | 5 | Background worker daemon (start, stop, status, trigger, enable) |
395+| `neural` | 5 | Neural pattern training (train, status, patterns, predict, optimize) |
396+| `security` | 6 | Security scanning (scan, audit, cve, threats, validate, report) |
397+| `performance` | 5 | Performance profiling (benchmark, profile, metrics, optimize, report) |
398+| `providers` | 5 | AI providers (list, add, remove, test, configure) |
399+| `plugins` | 5 | Plugin management (list, install, uninstall, enable, disable) |
400+| `deployment` | 5 | Deployment management (deploy, rollback, status, environments, release) |
401+| `embeddings` | 4 | Vector embeddings (embed, batch, search, init) — agentic-flow ONNX backend (speedup unverified, no benchmark) |
402+| `claims` | 4 | Claims-based authorization (check, grant, revoke, list) |
403+| `migrate` | 5 | V2 to V3 migration with rollback support |
404+| `process` | 4 | Background process management |
405+| `doctor` | 1 | System diagnostics with health checks |
406+| `completions` | 4 | Shell completions (bash, zsh, fish, powershell) |
407+
408+### Quick CLI Examples
409+
410+```bash
411+# Initialize project
412+npx claude-flow@v3alpha init --wizard
413+
414+# Start daemon with background workers
415+npx claude-flow@v3alpha daemon start
416+
417+# Spawn an agent
418+npx claude-flow@v3alpha agent spawn -t coder --name my-coder
419+
420+# Initialize swarm
421+npx claude-flow@v3alpha swarm init --v3-mode
422+
423+# Search memory (HNSW-indexed)
424+npx claude-flow@v3alpha memory search -q "authentication patterns"
425+
426+# System diagnostics
427+npx claude-flow@v3alpha doctor --fix
428+
429+# Security scan
430+npx claude-flow@v3alpha security scan --depth full
431+
432+# Performance benchmark
433+npx claude-flow@v3alpha performance benchmark --suite all
434+```
435+
436+## Headless Background Instances (claude -p)
437+
438+Use `claude -p` (print/pipe mode) to spawn headless Claude instances for parallel background work. These run non-interactively and return results to stdout.
439+
440+### Basic Usage
441+
442+```bash
443+# Single headless task
444+claude -p "Analyze the authentication module for security issues"
445+
446+# With model selection
447+claude -p --model haiku "Format this config file"
448+claude -p --model opus "Design the database schema for user management"
449+
450+# With output format
451+claude -p --output-format json "List all TODO comments in src/"
452+claude -p --output-format stream-json "Refactor the error handling in api.ts"
453+
454+# With budget limits
455+claude -p --max-budget-usd 0.50 "Run comprehensive security audit"
456+
457+# With specific tools allowed
458+claude -p --allowedTools "Read,Grep,Glob" "Find all files that import the auth module"
459+
460+# Skip permissions (sandboxed environments only)
461+claude -p --dangerously-skip-permissions "Fix all lint errors in src/"
462+```
463+
464+### Parallel Background Execution
465+
466+```bash
467+# Spawn multiple headless instances in parallel
468+claude -p "Analyze src/auth/ for vulnerabilities" &
469+claude -p "Write tests for src/api/endpoints.ts" &
470+claude -p "Review src/models/ for performance issues" &
471+wait # Wait for all to complete
472+
473+# With results captured
474+SECURITY=$(claude -p "Security audit of auth module" &)
475+TESTS=$(claude -p "Generate test coverage report" &)
476+PERF=$(claude -p "Profile memory usage in workers" &)
477+wait
478+echo "$SECURITY" "$TESTS" "$PERF"
479+```
480+
481+### Session Continuation
482+
483+```bash
484+# Start a task, resume later
485+claude -p --session-id "abc-123" "Start analyzing the codebase"
486+claude -p --resume "abc-123" "Continue with the test files"
487+
488+# Fork a session for parallel exploration
489+claude -p --resume "abc-123" --fork-session "Try approach A: event sourcing"
490+claude -p --resume "abc-123" --fork-session "Try approach B: CQRS pattern"
491+```
492+
493+### Key Flags
494+
495+| Flag | Purpose |
496+|------|---------|
497+| `-p, --print` | Non-interactive mode, print and exit |
498+| `--model <model>` | Select model (haiku, sonnet, opus) |
499+| `--output-format <fmt>` | Output: text, json, stream-json |
500+| `--max-budget-usd <amt>` | Spending cap per invocation |
501+| `--allowedTools <tools>` | Restrict available tools |
502+| `--append-system-prompt` | Add custom instructions |
503+| `--resume <id>` | Continue a previous session |
504+| `--fork-session` | Branch from resumed session |
505+| `--fallback-model <model>` | Auto-fallback if primary overloaded |
506+| `--permission-mode <mode>` | acceptEdits, bypassPermissions, plan, etc. |
507+| `--mcp-config <json>` | Load MCP servers from JSON |
508+
509+## Available Agents (60+ Types)
510+
511+### Core Development
512+`coder`, `reviewer`, `tester`, `planner`, `researcher`
513+
514+### V3 Specialized Agents
515+`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`
516+
517+### @claude-flow/security Module
518+CVE remediation, input validation, path security:
519+- `InputValidator` — Zod-based validation at boundaries
520+- `PathValidator` — Path traversal prevention
521+- `SafeExecutor` — Command injection protection
522+- `PasswordHasher` — bcrypt hashing
523+- `TokenGenerator` — Secure token generation
524+
525+### Token Optimizer (Agent Booster)
526+Integrates agentic-flow optimizations for 30-50% token reduction:
527+```typescript
528+import { getTokenOptimizer } from '@claude-flow/integration';
529+const optimizer = await getTokenOptimizer();
530+
531+// Compact context (32% fewer tokens)
532+const ctx = await optimizer.getCompactContext("auth patterns");
533+
534+// 352x faster edits = fewer retries
535+await optimizer.optimizedEdit(file, old, new, "typescript");
536+
537+// Optimal config (100% success rate)
538+const config = optimizer.getOptimalConfig(agentCount);
539+```
540+| Feature | Token Savings |
541+|---------|---------------|
542+| ReasoningBank retrieval | -32% |
543+| Agent Booster edits | -15% |
544+| Cache (95% hit rate) | -10% |
545+| Optimal batch size | -20% |
546+
547+### Swarm Coordination
548+`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`, `collective-intelligence-coordinator`, `swarm-memory-manager`
549+
550+### Consensus & Distributed
551+`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`, `consensus-builder`, `crdt-synchronizer`, `quorum-manager`, `security-manager`
552+
553+### Performance & Optimization
554+`perf-analyzer`, `performance-benchmarker`, `task-orchestrator`, `memory-coordinator`, `smart-agent`
555+
556+### GitHub & Repository
557+`github-modes`, `pr-manager`, `code-review-swarm`, `issue-tracker`, `release-manager`, `workflow-automation`, `project-board-sync`, `repo-architect`, `multi-repo-swarm`
558+
559+### SPARC Methodology
560+`sparc-coord`, `sparc-coder`, `specification`, `pseudocode`, `architecture`, `refinement`
561+
562+### Specialized Development
563+`backend-dev`, `mobile-dev`, `ml-developer`, `cicd-engineer`, `api-docs`, `system-architect`, `code-analyzer`, `base-template-generator`
564+
565+### Testing & Validation
566+`tdd-london-swarm`, `production-validator`
567+
568+## Agent Teams & Comms System
569+
570+Agent Teams turns Claude Code into a multi-agent system where named agents communicate in real-time via `SendMessage`. The comms system is the primary coordination mechanism — agents talk to each other, not just to the lead.
571+
572+### Architecture
573+
574+```
575+Team Lead (you)
576+ ├── SendMessage ←→ architect (named agent)
577+ ├── SendMessage ←→ developer (named agent)
578+ ├── SendMessage ←→ tester (named agent)
579+ └── SendMessage ←→ reviewer (named agent)
580+ ↕ agents can message each other by name
581+```
582+
583+### Core Principle: Named Agents + SendMessage
584+
585+Every agent MUST have a `name` so it's addressable. Communication happens via `SendMessage`, not polling or shared memory.
586+
587+```javascript
588+// STEP 1: Spawn named agents (all in ONE message, background)
589+Task({
590+ prompt: "Design the API. When done, send your design to 'developer' via SendMessage.",
591+ subagent_type: "system-architect",
592+ name: "architect",
593+ run_in_background: true
594+})
595+Task({
596+ prompt: "Wait for architect's design via SendMessage. Then implement it. Send code to 'tester'.",
597+ subagent_type: "coder",
598+ name: "developer",
599+ run_in_background: true
600+})
601+Task({
602+ prompt: "Wait for developer's code via SendMessage. Write tests. Send results to 'reviewer'.",
603+ subagent_type: "tester",
604+ name: "tester",
605+ run_in_background: true
606+})
607+
608+// STEP 2: Kick off the pipeline by messaging the first agent
609+SendMessage({
610+ to: "architect",
611+ summary: "Start API design",
612+ message: "Design a REST API for user management with CRUD endpoints. Send the design to 'developer' when done."
613+})
614+```
615+
616+### SendMessage Protocol
617+
618+```javascript
619+// Lead → Teammate: assign work
620+SendMessage({ to: "developer", summary: "Implement auth", message: "Build OAuth2 flow..." })
621+
622+// Lead → Teammate: redirect priorities
623+SendMessage({ to: "developer", summary: "Prioritize auth", message: "Auth endpoint is blocking tester, do it first." })
624+
625+// Lead → Teammate: provide context from another agent's results
626+SendMessage({ to: "tester", summary: "Architect output", message: "The architect designed these endpoints: [details]. Write tests for them." })
627+
628+// Lead → Teammate: graceful shutdown
629+SendMessage({ to: "developer", message: { type: "shutdown_request" } })
630+```
631+
632+### Coordination Patterns
633+
634+**Pipeline (A → B → C)** — each agent messages the next when done:
635+```
636+architect ──SendMessage──→ developer ──SendMessage──→ tester ──SendMessage──→ reviewer
637+```
638+Tell each agent WHO to message next in their prompt.
639+
640+**Fan-out / Fan-in** — lead spawns parallel agents, collects results:
641+```
642+ ┌→ researcher-1 ──→┐
643+lead ────┼→ researcher-2 ──→├──→ lead synthesizes
644+ └→ researcher-3 ──→┘
645+```
646+Spawn with `run_in_background: true`. Results arrive as task completions.
647+
648+**Supervisor / Worker** — lead assigns, workers report back:
649+```
650+lead ←──SendMessage──→ worker-1
651+lead ←──SendMessage──→ worker-2
652+lead ←──SendMessage──→ worker-3
653+```
654+Lead sends tasks via SendMessage, workers respond with results.
655+
656+### Agent Prompt Template (Comms-Aware)
657+
658+When spawning agents that need to coordinate, include comms instructions:
659+
660+```javascript
661+Task({
662+ prompt: `You are the architect for this feature team.
663+
664+YOUR TASK: Design the database schema for user management.
665+
666+COMMS PROTOCOL:
667+- When your design is ready, send it to "developer" via SendMessage
668+- If you need clarification, message the team lead (just output text)
669+- Include file paths and key decisions in your message
670+
671+DELIVERABLE: Schema design with entity relationships, indexes, and migration plan.`,
672+ subagent_type: "system-architect",
673+ name: "architect",
674+ run_in_background: true
675+})
676+```
677+
678+### Full Team Spawn Example
679+
680+```javascript
681+// Create shared task list first
682+TaskCreate({ subject: "Design schema", description: "...", activeForm: "Designing" })
683+TaskCreate({ subject: "Implement models", description: "...", activeForm: "Implementing" })
684+TaskCreate({ subject: "Write tests", description: "...", activeForm: "Testing" })
685+TaskCreate({ subject: "Security review", description: "...", activeForm: "Reviewing" })
686+
687+// Spawn ALL named agents in ONE message
688+Task({
689+ prompt: "Design the schema. SendMessage to 'developer' with your design when done. Update task #1.",
690+ subagent_type: "system-architect", name: "architect", run_in_background: true
691+})
692+Task({
693+ prompt: "Wait for schema from 'architect'. Implement models + endpoints. SendMessage to 'tester'. Update task #2.",
694+ subagent_type: "coder", name: "developer", run_in_background: true
695+})
696+Task({
697+ prompt: "Wait for code from 'developer'. Write integration tests. SendMessage results to 'security'. Update task #3.",
698+ subagent_type: "tester", name: "tester", run_in_background: true
699+})
700+Task({
701+ prompt: "Wait for test results from 'tester'. Review for vulnerabilities. Update task #4.",
702+ subagent_type: "security-auditor", name: "security", run_in_background: true
703+})
704+```
705+
706+### Agent Teams Hooks
707+
708+| Hook | Trigger | Purpose |
709+|------|---------|---------|
710+| `TeammateIdle` | Teammate finishes turn | Auto-assign pending tasks via SendMessage |
711+| `TaskCompleted` | Task marked complete | Train patterns, notify lead via SendMessage |
712+
713+```bash
714+npx claude-flow@v3alpha hooks teammate-idle --auto-assign true
715+npx claude-flow@v3alpha hooks task-completed -i task-123 --train-patterns true
716+```
717+
718+### Rules
719+
720+1. **Always name agents** — use `name: "role-name"` so they're addressable
721+2. **Comms over memory** — use SendMessage for real-time coordination, memory for persistence
722+3. **Pipeline prompts** — tell each agent WHO to message next and WHAT to send
723+4. **Spawn all at once** — all Task calls in ONE message with `run_in_background: true`
724+5. **Don't poll** — agents message back when done; wait for task completion notifications
725+6. **Graceful shutdown** — send `{ type: "shutdown_request" }` before TeamDelete
726+7. **Lead synthesizes** — when agents complete, review ALL results before responding to user
727+
728+## V3 Hooks System (17 Hooks + 12 Workers)
729+
730+### Hook Categories
731+
732+| Category | Hooks | Purpose |
733+|----------|-------|---------|
734+| **Core** | `pre-edit`, `post-edit`, `pre-command`, `post-command`, `pre-task`, `post-task` | Tool lifecycle |
735+| **Session** | `session-start`, `session-end`, `session-restore`, `notify` | Context management |
736+| **Intelligence** | `route`, `explain`, `pretrain`, `build-agents`, `transfer` | Neural learning |
737+| **Learning** | `intelligence` (trajectory-start/step/end, pattern-store/search, stats, attention) | Reinforcement |
738+| **Agent Teams** | `teammate-idle`, `task-completed` | Multi-agent coordination |
739+
740+### 12 Background Workers
741+
742+| Worker | Priority | Description |
743+|--------|----------|-------------|
744+| `ultralearn` | normal | Deep knowledge acquisition |
745+| `optimize` | high | Performance optimization |
746+| `consolidate` | low | Memory consolidation |
747+| `predict` | normal | Predictive preloading |
748+| `audit` | critical | Security analysis |
749+| `map` | normal | Codebase mapping |
750+| `preload` | low | Resource preloading |
751+| `deepdive` | normal | Deep code analysis |
752+| `document` | normal | Auto-documentation |
753+| `refactor` | normal | Refactoring suggestions |
754+| `benchmark` | normal | Performance benchmarking |
755+| `testgaps` | normal | Test coverage analysis |
756+
757+### Essential Hook Commands
758+
759+```bash
760+# Core hooks
761+npx claude-flow@v3alpha hooks pre-task --description "[task]"
762+npx claude-flow@v3alpha hooks post-task --task-id "[id]" --success true
763+npx claude-flow@v3alpha hooks post-edit --file "[file]" --train-patterns
764+
765+# Session management
766+npx claude-flow@v3alpha hooks session-start --session-id "[id]"
767+npx claude-flow@v3alpha hooks session-end --export-metrics true
768+npx claude-flow@v3alpha hooks session-restore --session-id "[id]"
769+
770+# Intelligence routing
771+npx claude-flow@v3alpha hooks route --task "[task]"
772+npx claude-flow@v3alpha hooks explain --topic "[topic]"
773+
774+# Neural learning
775+npx claude-flow@v3alpha hooks pretrain --model-type moe --epochs 10
776+npx claude-flow@v3alpha hooks build-agents --agent-types coder,tester
777+
778+# Background workers
779+npx claude-flow@v3alpha hooks worker list
780+npx claude-flow@v3alpha hooks worker dispatch --trigger audit
781+npx claude-flow@v3alpha hooks worker status
782+```
783+
784+## Intelligence System (RuVector)
785+
786+V3 includes the RuVector Intelligence System (measured numbers: see [audit](docs/reviews/intelligence-system-audit-2026-05-29.md) + [`scripts/benchmark-intelligence.mjs`](scripts/benchmark-intelligence.mjs)):
787+- **SONA**: Self-Optimizing Neural Architecture (measured 0.0043ms/adapt, target <0.05ms met)
788+- **MoE**: Mixture of Experts for specialized routing (gate converges — confidence 0.13→0.88 after rewards)
789+- **HNSW**: measured ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force (recall@10 ~0.99); ANN wins above the crossover, ruvector NAPI backend (WASM not active on test host)
790+- **EWC++**: Elastic Weight Consolidation (prevents forgetting)
791+- **Flash Attention**: integration available; speedup dropped from docs pending an in-tree benchmark (was: 2.49x–7.47x, inherited unverified from upstream — removed to avoid a credibility claim we can't reproduce)
792+
793+The 4-step intelligence pipeline:
794+1. **RETRIEVE** — Fetch relevant patterns via HNSW
795+2. **JUDGE** — Evaluate with verdicts (success/failure)
796+3. **DISTILL** — Extract key learnings via LoRA
797+4. **CONSOLIDATE** — Prevent catastrophic forgetting via EWC++
798+
799+## Embeddings Package (v3.0.0-alpha.12)
800+
801+Features:
802+- **sql.js**: Cross-platform SQLite persistent cache (WASM, no native compilation)
803+- **Document chunking**: Configurable overlap and size
804+- **Normalization**: L2, L1, min-max, z-score
805+- **Hyperbolic embeddings**: Poincare ball model for hierarchical data
806+- **agentic-flow ONNX integration**: speedup unverified (no benchmark; backend reported `onnx`, model all-MiniLM-L6-v2, 384-dim)
807+- **Neural substrate**: Integration with RuVector
808+
809+## Hive-Mind Consensus
810+
811+### Topologies
812+- `hierarchical` — Queen controls workers directly
813+- `mesh` — Fully connected peer network
814+- `hierarchical-mesh` — Hybrid (recommended)
815+- `adaptive` — Dynamic based on load
816+
817+### Consensus Strategies
818+- `byzantine` — BFT (tolerates f < n/3 faulty)
819+- `raft` — Leader-based (tolerates f < n/2)
820+- `gossip` — Epidemic for eventual consistency
821+- `crdt` — Conflict-free replicated data types
822+- `quorum` — Configurable quorum-based
823+
824+## V3 Performance Targets
825+
826+> 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".
827+
828+| Metric | Measured / Target | Status |
829+|--------|-------------------|--------|
830+| HNSW Search | ~1.9x at N=20k, ~3.2x–4.7x at N=5k vs brute force (recall@10 ~0.99); ties/loses below crossover | **Measured** (ruvector NAPI; 150x-12,500x NOT reproduced — was brute-force fallback) |
831+| Int8 Quantization | 3.84x compression, reconstruction cosine 0.99999 | **Measured** |
832+| RaBitQ Quantization | 32x compression, 0.60ms/query (14,760-vec index) | **Measured** |
833+| SONA Adaptation | 0.0043ms/adapt (target <0.05ms met) | **Measured** |
834+| MoE Gate | converges — confidence 0.13→0.88, Q 0→99.8 after rewards | **Measured** |
835+| Flash Attention | integration available; measured speedup pending benchmark | **Not measured** — prior "2.49x–7.47x" figure was inherited from upstream marketing, never reproduced in-tree; dropped to avoid a credibility claim we can't verify |
836+| MCP Response | <100ms | target |
837+| CLI Startup | <500ms | target |
838+
839+## Environment Variables
840+
841+```bash
842+# Configuration
843+CLAUDE_FLOW_CONFIG=./claude-flow.config.json
844+CLAUDE_FLOW_LOG_LEVEL=info
845+
846+# Provider API Keys
847+ANTHROPIC_API_KEY=sk-ant-...
848+OPENAI_API_KEY=sk-...
849+GOOGLE_API_KEY=...
850+
851+# MCP Server
852+CLAUDE_FLOW_MCP_PORT=3000
853+CLAUDE_FLOW_MCP_HOST=localhost
854+CLAUDE_FLOW_MCP_TRANSPORT=stdio
855+
856+# Memory
857+CLAUDE_FLOW_MEMORY_BACKEND=hybrid
858+CLAUDE_FLOW_MEMORY_PATH=./data/memory
859+```
860+
861+## Doctor Health Checks
862+
863+Run `npx claude-flow@v3alpha doctor` to check:
864+- Node.js version (20+)
865+- npm version (9+)
866+- Git installation
867+- Config file validity
868+- Daemon status
869+- Memory database
870+- API keys
871+- MCP servers
872+- Disk space
873+- TypeScript installation
874+
875+## Quick Setup
876+
877+```bash
878+# Add MCP servers
879+claude mcp add claude-flow -- npx -y ruflo@latest mcp start
880+claude mcp add ruv-swarm npx ruv-swarm mcp start # Optional
881+claude mcp add flow-nexus npx flow-nexus@latest mcp start # Optional
882+
883+# Start daemon
884+npx claude-flow@v3alpha daemon start
885+
886+# Run doctor
887+npx claude-flow@v3alpha doctor --fix
888+```
889+
890+## Claude Code vs MCP Tools
891+
892+### Claude Code Handles ALL EXECUTION:
893+- **Task tool**: Spawn and run agents concurrently
894+- File operations (Read, Write, Edit, MultiEdit, Glob, Grep)
895+- Code generation and programming
896+- Bash commands and system operations
897+- TodoWrite and task management
898+- Git operations
899+
900+### MCP Tools ONLY COORDINATE:
901+- Swarm initialization (topology setup)
902+- Agent type definitions
903+- Task orchestration
904+- Memory management
905+- Neural features
906+- Performance tracking
907+
908+- Keep MCP for coordination strategy only — use Claude Code's Task tool for real execution
909+
910+## Claude Code ↔ AgentDB Memory Bridge
911+
912+Claude Code's auto-memory (`~/.claude/projects/*/memory/*.md`) is bridged to AgentDB with ONNX vector embeddings for semantic search.
913+
914+### MCP Tools
915+
916+| Tool | Description |
917+|------|-------------|
918+| `memory_import_claude` | Import Claude Code memories into AgentDB with 384-dim ONNX embeddings. Use `allProjects: true` to import from ALL projects. |
919+| `memory_bridge_status` | Show bridge health — Claude files, AgentDB entries, SONA state, connection status |
920+| `memory_search_unified` | Semantic search across ALL namespaces (claude-memories, auto-memory, patterns, tasks, feedback) |
921+
922+### Auto-Import on Session Start
923+
924+The `SessionStart` hook automatically imports current project's memories into AgentDB. For manual import of all projects:
925+
926+```bash
927+# Via MCP tool (from Claude Code)
928+memory_import_claude({ allProjects: true })
929+
930+# Via helper hook (from terminal)
931+node .claude/helpers/auto-memory-hook.mjs import-all
932+```
933+
934+### Unified Search
935+
936+Search across both Claude Code memories and AgentDB entries:
937+
938+```bash
939+# Via MCP tool
940+memory_search_unified({ query: "authentication security", limit: 5 })
941+
942+# Results include source attribution: claude-code, auto-memory, or agentdb
943+```
944+
945+### Intelligence Pipeline
946+
947+| Component | Status | Details |
948+|-----------|--------|---------|
949+| ONNX Embeddings | Active | all-MiniLM-L6-v2, 384 dimensions |
950+| SONA Learning | Active | Pattern matching + trajectory recording |
951+| ReasoningBank | Active | Pattern storage with file persistence |
952+| AgentDB sql.js | Active | SQLite with vector_indexes table |
953+
954+## Publishing to npm
955+
956+### Versioning policy (stable releases — alpha series ended at 3.7.0-alpha.81, 2026-05-23)
957+
958+- **From 3.7.0 onward we ship stable semver**, NOT alpha pre-releases.
959+- Bump rules (semver discipline):
960+ - **PATCH** (3.7.0 → 3.7.1): bug fixes only, no API change, no schema change
961+ - **MINOR** (3.7.0 → 3.8.0): backward-compatible additions (new MCP tool, new flag, new agent type)
962+ - **MAJOR** (3.x → 4.0.0): breaking change in CLI surface, MCP tool signature, file layout, or default behavior
963+- Default tag is `latest` (no `--tag alpha`). The `alpha` and `v3alpha` dist-tags continue to exist for historical compatibility — point them at the same version as `latest`.
964+- Never publish a pre-release (`-alpha.N`, `-beta.N`, `-rc.N`) unless the user explicitly asks for a pre-release flow.
965+
966+### Publishing Rules
967+
968+- The normal public release train is exactly THREE packages:
969+ `@claude-flow/cli`, `claude-flow`, and `ruflo`.
970+- Internal `@claude-flow/*` components are bundled into the public artifacts;
971+ do not publish them standalone as part of the normal release.
972+- MUST update ALL dist-tags for ALL THREE packages after publishing (latest + alpha + v3alpha all point to the same version)
973+- Publish order: `@claude-flow/cli` first, then `claude-flow` (umbrella), then `ruflo` (alias umbrella)
974+- MUST run verification for ALL THREE before telling user publishing is complete
975+- Run `node scripts/audit-umbrella-version-lockstep.mjs` before packing or
976+ publishing.
977+- Publish from a clean reviewed commit/tag-equivalent worktree. Do not ship
978+ unrelated uncommitted changes.
979+- A fresh worktree has two separate dependency trees to install before anything
980+ builds: `npm install` at repo root (npm workspaces), AND `pnpm install` inside
981+ `v3/` (a separate pnpm workspace — root `prepare-root-publish.mjs` shells out to
982+ `pnpm --filter` to build `v3/@claude-flow/{shared,hooks,guidance}`, which fails
983+ with `spawn ENOENT` on `tsc` if `v3/node_modules` was never populated).
984+- Use the existing authenticated `ruvnet` npm session. Do not replace it with a
985+ token from another GCP project.
986+
987+**`npm publish` auth — FIXED (2026-07-30):** use the `NPM_TOKEN` secret directly,
988+via a throwaway `.npmrc` with `NPM_CONFIG_USERCONFIG` — same pattern as the
989+helpers-signing-key handling. It is mirrored in two GCP projects — `ruv-dev`
990+(version 3+) and `cognitum-20260110` (version 7+) — so either project's copy
991+is current; use whichever `gcloud` session is already authenticated. This is a
992+granular access token ("ruflo publishjing", expires 2026-10-28) with
993+`package: write` + `bypass_2fa: true`, scoped broadly enough to cover
994+`@claude-flow/cli`, `claude-flow`, and `ruflo` (plus the `cognitum`/
995+`cognitum-one` orgs). Confirmed end-to-end against the real registry (not just
996+a permissions probe): `npm publish` for `@claude-flow/cli` succeeded via this
997+token with zero OTP/WebAuthn prompt, and
998+`npm dist-tag add` against both a scoped (`@claude-flow/cli`) and unscoped
999+(`claude-flow`) package also went through with no prompt.
1000+
1001+**Why the earlier `NPM_TOKEN` version failed:** versions 1/2 of that secret
1002+were older classic automation tokens, and npm has been restricting tokens that
1003+bypass 2FA for writes account-wide (the login flow prints this notice —
1004+`gh.io/npm-gat-bypass2fa-deprecation`). Version 3 is a **granular access
1005+token** created explicitly for this purpose, which is npm's supported
1006+replacement path (its own 2FA-bypass flag still works for a granular token,
1007+unlike the deprecated classic automation tokens). If this token's `bypass_2fa`
1008+flag or scope ever gets narrowed/expired (check expiry above), the fallback
1009+is the WebAuthn dance below — but try this path first every time.
1010+
1011+```bash
1012+gcloud secrets versions access latest --secret=NPM_TOKEN --project=ruv-dev > /tmp/.npmrc-publish-raw
1013+printf '//registry.npmjs.org/:_authToken=%s\n' "$(cat /tmp/.npmrc-publish-raw)" > /tmp/.npmrc-publish
1014+rm -f /tmp/.npmrc-publish-raw
1015+NPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm publish # from the package dir, with signing-key env vars for @claude-flow/cli
1016+NPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> alpha
1017+NPM_CONFIG_USERCONFIG=/tmp/.npmrc-publish npm dist-tag add <pkg>@<version> v3alpha
1018+shred -u /tmp/.npmrc-publish 2>/dev/null || rm -f /tmp/.npmrc-publish # ALWAYS clean up, same discipline as the signing key
1019+```
1020+
1021+**Fallback — WebAuthn procedure, if the token above is dead:** the `ruvnet`
1022+account's 2FA method is a WebAuthn security key, not TOTP (no numeric
1023+`--otp=<code>` exists). This must be driven by the human (an agent cannot
1024+approve a WebAuthn browser prompt):
1025+1. Human goes to npmjs.com → account 2FA settings → turns OFF "Require
1026+ two-factor authentication for write actions" (narrows to auth-only, not a
1027+ full 2FA disable), then runs `npm login` in their own terminal to refresh
1028+ the session under the new setting.
1029+2. Agent can then run `npm publish` directly via Bash with no further prompt.
1030+3. **`npm dist-tag add` still requires a fresh WebAuthn approval PER CALL**
1031+ regardless of the write-2FA setting — 6 individual browser approvals for a
1032+ 3-package release (alpha + v3alpha × 3), not 1. Tell the human up front.
1033+- After every dist-tag call (or if unsure), verify with
1034+ `npm view <pkg> dist-tags --json` — don't trust the CLI's own stdout alone, since
1035+ a WebAuthn prompt that's still pending in the browser produces no terminal
1036+ output an agent can see.
1037+- Confirm the version actually landed (`npm view <pkg>@<version> version`) before
1038+ telling the user publishing succeeded, same reasoning: a mid-publish approval
1039+ that never gets answered fails silently from an agent's point of view.
1040+
1041+**Helpers signing key (required for `@claude-flow/cli` publish):** `npm publish`'s
1042+`prepublishOnly` runs `scripts/sign-helpers.mjs`, which needs a private key to sign
1043+`.claude/helpers/helpers.manifest.json`. The secret lives in GCP Secret Manager in the
1044+**`ruv-dev`** project (not `cognitum-20260110` or `claude-flow` — checked both, not there),
1045+secret name `ruflo-helpers-signing-key`:
1046+
1047+```bash
1048+cd v3/@claude-flow/cli
1049+RUFLO_HELPERS_SIGNING_SECRET=ruflo-helpers-signing-key RUFLO_HELPERS_SIGNING_PROJECT=ruv-dev \
1050+ npm publish
1051+```
1052+
1053+(`ruv-dev` also holds `ruflo-config-signing-key`; do not replace the existing
1054+authenticated npm session with a token from another project.)
1055+
1056+**Handling the signing key without leaking it (learned 2026-07-14, hard way):**
1057+an earlier Windows path invoked `gcloud` without its required `.cmd` suffix. The
1058+fallback command printed the PEM into captured tool output and a session transcript.
1059+GCP secret v1 was destroyed and a fresh v2 was rotated in (commit 0052b1b06 /
1060+PR #2673). `sign-helpers.mjs` now selects `gcloud.cmd` on Windows and supports a
1061+stdin-only fallback. **Rules:**
1062+- NEVER invoke `gcloud secrets versions access` in a way that lets the payload reach
1063+ tool output. Use the built-in `RUFLO_HELPERS_SIGNING_SECRET` path above, or pipe
1064+ directly into the signer:
1065+ `gcloud secrets versions access latest --secret=ruflo-helpers-signing-key --project=ruv-dev | node scripts/sign-helpers.mjs --stdin-key`.
1066+- `--stdin-key` refuses interactive entry, validates Ed25519 key type, and never
1067+ echoes parser input. A local file via `RUFLO_HELPERS_SIGNING_KEY` remains the
1068+ air-gapped fallback.
1069+- If a rotation IS needed, keep the private half in `~/.ruflo/helpers-signing.key`
1070+ only, print ONLY the public half (via `Ed25519 pub export` from Node crypto), upload
1071+ new private via `gcloud secrets versions add … --data-file=`, then
1072+ `gcloud secrets versions destroy <old>` to make the old irrecoverable.
1073+
1074+**Windows `prepublishOnly` failure (learned 2026-07-14):** the CLI's `prepublishOnly`
1075+chain (`cp ../../../README.md ./README.md && rm -rf plugins && mkdir -p plugins && cp -r ...`)
1076+is POSIX-shell-only. On Windows, npm runs it via `cmd.exe /d /s /c` which chokes on
1077+`mkdir -p` (interprets `-p` as a directory name) and `cp -r` (no such command). Two
1078+workarounds until the script is rewritten in cross-platform Node:
1079+1. Run the prep steps manually in Git Bash, then `npm publish --ignore-scripts`.
1080+2. Or use a POSIX shell for the whole publish: `SHELL=bash npm publish` — but this
1081+ doesn't always take effect on Windows depending on npm version.
1082+Option 1 is what worked for v3.29.0. Track proper fix in ruvnet/ruflo issue for
1083+cross-platform prepublish.
1084+
1085+**Concurrent-session helper corruption (real, observed, be paranoid):** multiple Claude Code
1086+sessions can have their own `npm exec @claude-flow/cli@latest mcp start` MCP server running
1087+concurrently with `cwd` inside this repo (check with `readlink /proc/<pid>/cwd` on
1088+`pgrep -f "npm exec @claude-flow/cli@latest mcp start"`). If one of those resolved an older
1089+cached `@latest` (predating the `semver.gte` downgrade-guard in
1090+`helper-refresh.ts:autoRefreshHelpersIfStale`), it will silently overwrite this repo's
1091+hand-maintained `.claude/helpers/hook-handler.cjs` / `intelligence.cjs` (root AND package
1092+copies) — and `helpers.manifest.json` + `.helpers-version` — with its own older bundled
1093+content, mid-session, with no warning. Observed live 2026-07-13: this happened *twice* in
1094+one publish flow, once right after a manual revert and once right after signing (silently
1095+invalidating a freshly-signed manifest). **Mitigation:** never trust the on-disk state of
1096+those files between tool calls — `git diff --stat` them immediately before any `git add`/
1097+`sign-helpers.mjs`/`npm publish` step, `git checkout HEAD --` revert if dirty, and chain
1098+revert → sign → verify → add → commit as ONE bash invocation (`&&`-joined) to minimize the
1099+race window. `npm publish`'s own `prepublishOnly` re-signs fresh at pack time regardless, so
1100+what matters is the on-disk state at the *exact moment* `npm publish` runs, not before.
1101+
1102+```bash
1103+# Replace 3.7.1 below with your chosen stable version (patch/minor/major per the rules above)
1104+
1105+# STEP 1: Build and publish @claude-flow/cli
1106+cd v3/@claude-flow/cli
1107+npm version 3.7.1 --no-git-tag-version
1108+npm run build
1109+npm publish # default tag is `latest` — no --tag flag
1110+npm dist-tag add @claude-flow/cli@3.7.1 alpha # historical compat
1111+npm dist-tag add @claude-flow/cli@3.7.1 v3alpha # historical compat
1112+
1113+# STEP 2: Publish claude-flow umbrella
1114+cd /Users/cohen/Projects/ruflo # or your repo root
1115+npm version 3.7.1 --no-git-tag-version
1116+npm publish
1117+npm dist-tag add claude-flow@3.7.1 alpha
1118+npm dist-tag add claude-flow@3.7.1 v3alpha
1119+
1120+# STEP 3: Publish ruflo wrapper (CRITICAL — DON'T FORGET — this is what users run)
1121+cd ruflo
1122+npm version 3.7.1 --no-git-tag-version
1123+npm publish
1124+npm dist-tag add ruflo@3.7.1 alpha
1125+npm dist-tag add ruflo@3.7.1 v3alpha
1126+```
1127+
1128+**Verification (run before telling user publishing is complete):**
1129+
1130+```bash
1131+for pkg in @claude-flow/cli claude-flow ruflo; do
1132+ echo "$pkg: $(npm view $pkg@latest version)"
1133+ npm view $pkg dist-tags --json
1134+done
1135+# All three must show latest === alpha === v3alpha === new version
1136+```
1137+
1138+### All Tags That Must Be Updated
1139+
1140+| Package | Tag | Command Users Run |
1141+|---------|-----|-------------------|
1142+| `@claude-flow/cli` | `latest` | `npx @claude-flow/cli@latest` |
1143+| `@claude-flow/cli` | `alpha` | `npx @claude-flow/cli@alpha` (legacy compat) |
1144+| `@claude-flow/cli` | `v3alpha` | `npx @claude-flow/cli@v3alpha` (legacy compat) |
1145+| `claude-flow` | `latest` | `npx claude-flow@latest` |
1146+| `claude-flow` | `alpha` | `npx claude-flow@alpha` (legacy compat) |
1147+| `claude-flow` | `v3alpha` | `npx claude-flow@v3alpha` (legacy compat) |
1148+| `ruflo` | `latest` | `npx ruflo@latest` |
1149+| `ruflo` | `alpha` | `npx ruflo@alpha` (legacy compat) |
1150+| `ruflo` | `v3alpha` | `npx ruflo@v3alpha` (legacy compat) |
1151+
1152+- Never forget the `ruflo` package — it's the thin wrapper users actually run via `npx ruflo`
1153+- The legacy `alpha` and `v3alpha` tags MUST stay pointed at the latest stable so old install commands keep working
1154+- `ruflo` source is in `/ruflo/` — it depends on `@claude-flow/cli`
1155+- Also remember to update `ruflo/package.json` overrides when adding new pinned transitives (see #2112 lesson — root overrides do NOT propagate to the published `ruflo` wrapper)
1156+
1157+### GitHub Release after publish
1158+
1159+Every stable bump SHOULD have a matching `gh release create v<version>` with consolidated release notes pointing at the gist if one exists. Example:
1160+
1161+```bash
1162+git tag v3.7.1 main
1163+git push origin v3.7.1
1164+gh release create v3.7.1 --title "v3.7.1 — <one-line headline>" \
1165+ --notes-file /tmp/release-notes.md
1166+```
1167+
1168+## Plugin Registry Maintenance (IPFS/Pinata)
1169+
1170+The plugin registry is stored on IPFS via Pinata for decentralized, immutable distribution.
1171+
1172+### Registry Location
1173+- **Current CID**: Stored in `v3/@claude-flow/cli/src/plugins/store/discovery.ts`
1174+- **Gateway**: `https://gateway.pinata.cloud/ipfs/{CID}`
1175+- **Format**: JSON with plugin metadata, categories, featured/trending lists
1176+
1177+### Required Environment Variables
1178+Add to `.env` (NEVER commit actual values):
1179+```bash
1180+PINATA_API_KEY=your-api-key
1181+PINATA_API_SECRET=your-api-secret
1182+PINATA_API_JWT=your-jwt-token
1183+```
1184+
1185+## Plugin Registry Operations
1186+
1187+### Adding a New Plugin to Registry
1188+
1189+1. **Fetch current registry**:
1190+```bash
1191+curl -s "https://gateway.pinata.cloud/ipfs/$(grep LIVE_REGISTRY_CID v3/@claude-flow/cli/src/plugins/store/discovery.ts | cut -d"'" -f2)" > /tmp/registry.json
1192+```
1193+
1194+2. **Add plugin entry** to the `plugins` array:
1195+```json
1196+{
1197+ "id": "@claude-flow/your-plugin",
1198+ "name": "@claude-flow/your-plugin",
1199+ "displayName": "Your Plugin",
1200+ "description": "Plugin description",
1201+ "version": "1.0.0-alpha.1",
1202+ "size": 100000,
1203+ "checksum": "sha256:abc123",
1204+ "author": {"id": "claude-flow-team", "displayName": "Claude Flow Team", "verified": true},
1205+ "license": "MIT",
1206+ "categories": ["official"],
1207+ "tags": ["your", "tags"],
1208+ "downloads": 0,
1209+ "rating": 5,
1210+ "lastUpdated": "2026-01-25T00:00:00.000Z",
1211+ "minClaudeFlowVersion": "3.0.0",
1212+ "type": "integration",
1213+ "hooks": [],
1214+ "commands": [],
1215+ "permissions": ["memory"],
1216+ "exports": ["YourExport"],
1217+ "verified": true,
1218+ "trustLevel": "official"
1219+}
1220+```
1221+
1222+3. **Update counts and arrays**:
1223+ - Increment `totalPlugins`
1224+ - Add to `official` array
1225+ - Add to `featured`/`newest` if applicable
1226+ - Update category `pluginCount`
1227+
1228+4. **Upload to Pinata** (read credentials from .env):
1229+```bash
1230+# Source credentials from .env
1231+PINATA_JWT=$(grep "^PINATA_API_JWT=" .env | cut -d'=' -f2-)
1232+
1233+# Upload updated registry
1234+curl -X POST "https://api.pinata.cloud/pinning/pinJSONToIPFS" \
1235+ -H "Authorization: Bearer $PINATA_JWT" \
1236+ -H "Content-Type: application/json" \
1237+ -d @/tmp/registry.json
1238+```
1239+
1240+5. **Update discovery.ts** with new CID:
1241+```typescript
1242+export const LIVE_REGISTRY_CID = 'NEW_CID_FROM_PINATA';
1243+```
1244+
1245+6. **Also update demo registry** in discovery.ts `demoPluginRegistry` for offline fallback
1246+
1247+### Security Rules
1248+- NEVER hardcode API keys in scripts or source files
1249+- NEVER commit .env (already in .gitignore)
1250+- Always source credentials from environment at runtime
1251+- Always delete temporary scripts after one-time uploads
1252+
1253+### Verification
1254+```bash
1255+# Verify new registry is accessible
1256+curl -s "https://gateway.pinata.cloud/ipfs/{NEW_CID}" | jq '.totalPlugins'
1257+```
1258+
1259+## MetaHarness Integration (ADR-150)
1260+
1261+Ruflo integrates with the upstream `metaharness` / `@metaharness/*` ecosystem as a sibling agent-harness scaffolding system (same author, designed around ruflo's primitives). MetaHarness packages are optional peer dependencies and are never required at runtime.
1262+
1263+### Architectural constraint (load-bearing)
1264+
1265+**Ruflo remains operational if every MetaHarness package is removed.** Four rules:
1266+1. **Removable**: `npm ls --without @metaharness/*` must still produce a working CLI
1267+2. **Optional in package.json**: `@metaharness/*` packages MUST be optional peers, never normal dependencies
1268+3. **Graceful degradation**: every code path that touches MetaHarness catches `MODULE_NOT_FOUND` and falls back
1269+4. **CI gate**: `.github/workflows/no-metaharness-smoke.yml` enforces all three by static grep + runtime drill on every PR
1270+
1271+### Command + tool surface
1272+
1273+```bash
1274+# CLI subcommands (npx ruflo metaharness …)
1275+npx ruflo metaharness score # 5-dim readiness scorecard
1276+npx ruflo metaharness genome # 7-section categorical report
1277+npx ruflo metaharness mcp-scan --fail-on high # static security findings
1278+npx ruflo metaharness threat-model # enterprise threat report
1279+npx ruflo metaharness oia-audit --alert-on-worst high
1280+ # composite weekly audit → memory
1281+npx ruflo metaharness audit-list --since 30d # enumerate audit records
1282+npx ruflo metaharness audit-trend \ # diff two audits (drift)
1283+ --baseline-key <a> --current-key <b> --alert-on-worsening \
1284+ --alert-on-distance-below 0.85 # iter 38 — structural-distance gate (ADR-152 §3.1)
1285+npx ruflo metaharness similarity \ # iter 36 — ADR-152 §3.1 weighted similarity
1286+ --a a.json --b b.json [--per-dimension] [--alert-below 0.5]
1287+npx ruflo metaharness drift-from-history \ # iter 53 — 1-command drift (composes 3 primitives)
1288+ [--baseline-since 7d] [--baseline-key <key>] [--baseline-file <path>] \
1289+ [--threshold 0.95] [--alert-on-new-severity high] [--dry-run]
1290+ # iter 66 — --baseline-key skips audit-list (~14x faster)
1291+ # iter 67 — --baseline-file skips memory entirely (~19x faster)
1292+ # iter 78 — --alert-on-new-severity adds orthogonal finding-severity gate
1293+npx ruflo metaharness mint --name foo --template vertical:coding --confirm
1294+npx ruflo metaharness redblue init # @metaharness/redblue — scaffold redblue.yaml
1295+npx ruflo metaharness redblue run --mock-judge --tests 10
1296+ # $0 marker-fixture path (CI / offline)
1297+npx ruflo metaharness redblue run --tests 50 --patch
1298+ # real model judge (needs OPENROUTER_API_KEY,
1299+ # capped by max_cost_usd, default $3)
1300+npx ruflo metaharness redblue attack prompt --count 3
1301+ # preview generated attack cases (no target call)
1302+npx ruflo metaharness redblue patch --mock-judge # baseline → blue-team patch → retest delta
1303+npx ruflo metaharness redblue report --in report.json
1304+ # render existing report as markdown
1305+npx ruflo metaharness learn --host claude-code --model haiku --slice slices/lite.json
1306+ # metaharness@0.3.0 / upstream ADR-235 —
1307+ # GEPA learning run; $0 dry-run default,
1308+ # --run to spend; needs a metaharness
1309+ # repo checkout (--repo / $METAHARNESS_REPO)
1310+npx ruflo metaharness gepa --op genome # darwin@0.8.0 GEPA library — load + validate
1311+ # the shipped cand-6 genome (or --path <f>)
1312+npx ruflo metaharness gepa --op render # genome → the system prompt it compiles to
1313+npx ruflo metaharness gepa --op analyze --transcript run.json
1314+ # classify failure modes in a transcript
1315+npx ruflo metaharness evolve --bench .harness/bench.json
1316+ # Darwin proposes candidates; governed gates decide
1317+npx ruflo metaharness bench verify --path .harness/bench.json
1318+ # create or verify stable benchmark corpora
1319+npx ruflo metaharness flywheel run --proposer auto --max-concurrency 2
1320+ # bounded concurrent evaluation; does not promote
1321+npx ruflo metaharness flywheel receipts # inspect immutable evaluation receipts
1322+npx ruflo metaharness flywheel promote <receipt-id> \
1323+ --public-key ./approved-ed25519-public.pem --confirm
1324+ # explicit policy-authorized atomic promotion
1325+
1326+# Dedicated command
1327+npx ruflo eject --name my-harness # lift ruflo project → standalone harness
1328+ # dry-run by default; refuses in-repo target
1329+
1330+# Doctor health check
1331+npx ruflo doctor --component metaharness # report metaharness availability + version
1332+
1333+# MCP tools (callable by Claude Code agents)
1334+mcp__claude-flow__metaharness_score
1335+mcp__claude-flow__metaharness_genome
1336+mcp__claude-flow__metaharness_mcp_scan
1337+mcp__claude-flow__metaharness_threat_model
1338+mcp__claude-flow__metaharness_oia_audit
1339+mcp__claude-flow__metaharness_audit_list
1340+mcp__claude-flow__metaharness_audit_trend
1341+mcp__claude-flow__metaharness_similarity # iter 36 — ADR-152 §3.1 genome similarity
1342+mcp__claude-flow__metaharness_drift_from_history # iter 53 — 1-command drift detection
1343+mcp__claude-flow__metaharness_bench # ADR-153 — create/verify bench suites for evolve --bench
1344+mcp__claude-flow__metaharness_evolve # MAP-Elites driver — evolve a harness across bench suites
1345+mcp__claude-flow__metaharness_security_bench # security-focused benchmark suite gate
1346+mcp__claude-flow__metaharness_redblue # @metaharness/redblue — adversarial red/blue LLM testing (init|run|patch|attack|report)
1347+mcp__claude-flow__metaharness_learn # metaharness@0.3.0 — GEPA learning run ($0 dry-run default; run=true to spend)
1348+mcp__claude-flow__metaharness_gepa # darwin@0.8.0 — GEPA genome ops (genome|validate|render|analyze); gepaOptimize stays library-only
1349+mcp__claude-flow__metaharness_flywheel # ADR-322 — evaluate concurrently, inspect receipts/ledger, or explicitly promote
1350+```
1351+
1352+### Routing integration (ADR-148/149)
1353+
1354+`@metaharness/router@~0.3.2` is wired as the cost-optimal model router behind the `CLAUDE_FLOW_ROUTER_NEURAL=1` triple-gate. The `routedBy` field on every routing decision carries `'metaharness-knn' | 'metaharness-krr' | 'fastgrnn'` when the neural path is active.
1355+
1356+### SelfEvolvingRouter parallel-logging (ADR-150 Phase 2)
1357+
1358+When `CLAUDE_FLOW_ROUTER_PARALLEL_LOG=1` is set, every `route()` call writes a paired-decision row (bandit pick + neural-augmented pick + outcome) to `.swarm/router-parallel.jsonl`. Analyze with:
1359+
1360+```bash
1361+node plugins/ruflo-metaharness/scripts/router-parallel-analyze.mjs \
1362+ --input .swarm/router-parallel.jsonl --strict
1363+```
1364+
1365+The 3-criteria AND-gate from ADR-150 review-round-1: `quality > 2% AND cost < 1% AND latency < 5%`. Exit 1 in `--strict` mode if any criterion fails — promotion gate.
1366+
1367+### CI workflows
1368+
1369+- `metaharness-ci.yml` — score / mcp-scan / router-compat / eject-dryrun jobs on every PR touching `plugins/ruflo-metaharness/**`
1370+- `no-metaharness-smoke.yml` — enforces the four architectural-constraint rules above on every PR
1371+- `oia-audit-weekly.yml` — Sundays 04:17 UTC, runs composite audit, uploads 90-day artifact
1372+
1373+### Cross-references
1374+
1375+- [ADR-150](v3/docs/adr/ADR-150-metaharness-integration-surfaces.md) — decision + implementation notes
1376+- [Issue #2399](https://github.com/ruvnet/ruflo/issues/2399) — phase tracker
1377+- [Research gist](https://gist.github.com/ruvnet/19d166ff9acf368c9da4172d91ac9113) — graded evidence
1378+- Upstream: `github.com/ruvnet/agent-harness-generator`
1379+
1380+## Optional Plugins (20 Available)
1381+
1382+Plugins are distributed via IPFS and can be installed with the CLI. Browse and install from the official registry:
1383+
1384+```bash
1385+# List all available plugins
1386+npx claude-flow@v3alpha plugins list
1387+
1388+# Install a plugin
1389+npx claude-flow@v3alpha plugins install @claude-flow/plugin-name
1390+
1391+# Enable/disable
1392+npx claude-flow@v3alpha plugins enable @claude-flow/plugin-name
1393+npx claude-flow@v3alpha plugins disable @claude-flow/plugin-name
1394+```
1395+
1396+### Core Plugins
1397+
1398+| Plugin | Version | Description |
1399+|--------|---------|-------------|
1400+| `@claude-flow/embeddings` | 3.0.0-alpha.1 | Vector embeddings with sql.js, HNSW, hyperbolic support |
1401+| `@claude-flow/security` | 3.0.0-alpha.1 | Input validation, path security, CVE remediation |
1402+| `@claude-flow/claims` | 3.0.0-alpha.8 | Claims-based authorization (check, grant, revoke, list) |
1403+| `@claude-flow/neural` | 3.0.0-alpha.7 | Neural pattern training (SONA, MoE, EWC++) |
1404+| `@claude-flow/plugins` | 3.0.0-alpha.1 | Plugin system core (manager, discovery, store) |
1405+| `@claude-flow/performance` | 3.0.0-alpha.1 | Performance profiling and benchmarking |
1406+
1407+### Integration Plugins
1408+
1409+| Plugin | Version | Description |
1410+|--------|---------|-------------|
1411+| `@claude-flow/plugin-agentic-qe` | 3.0.0-alpha.4 | Agentic quality engineering integration |
1412+| `@claude-flow/plugin-prime-radiant` | 0.1.5 | Prime Radiant intelligence integration |
1413+| `@claude-flow/plugin-gastown-bridge` | 3.0.0-alpha.1 | Gastown bridge protocol integration |
1414+| `@claude-flow/teammate-plugin` | 1.0.0-alpha.1 | Multi-agent teammate coordination |
1415+| `@claude-flow/plugin-code-intelligence` | 0.1.0 | Advanced code analysis and intelligence |
1416+| `@claude-flow/plugin-test-intelligence` | 0.1.0 | Intelligent test generation and gap analysis |
1417+| `@claude-flow/plugin-perf-optimizer` | 0.1.0 | Performance optimization automation |
1418+| `@claude-flow/plugin-neural-coordinator` | 0.1.0 | Neural network coordination across agents |
1419+| `@claude-flow/plugin-cognitive-kernel` | 0.1.0 | Core cognitive processing kernel |
1420+| `@claude-flow/plugin-quantum-optimizer` | 0.1.0 | Quantum-inspired optimization algorithms |
1421+| `@claude-flow/plugin-hyperbolic-reasoning` | 0.1.0 | Hyperbolic space reasoning for hierarchical data |
1422+
1423+### Domain-Specific Plugins
1424+
1425+| Plugin | Version | Description |
1426+|--------|---------|-------------|
1427+| `@claude-flow/plugin-healthcare-clinical` | 0.1.0 | Healthcare clinical workflow automation |
1428+| `@claude-flow/plugin-financial-risk` | 0.1.0 | Financial risk assessment and modeling |
1429+| `@claude-flow/plugin-legal-contracts` | 0.1.0 | Legal contract analysis and generation |
1430+
1431+### Plugin Development
1432+
1433+```bash
1434+# Create a new plugin from template
1435+npx claude-flow@v3alpha plugins create my-plugin
1436+
1437+# Test locally
1438+npx claude-flow@v3alpha plugins install ./path/to/my-plugin
1439+
1440+# Publish to registry (requires Pinata credentials)
1441+npx claude-flow@v3alpha plugins publish
1442+```
1443+
1444+Registry source: IPFS via Pinata (`QmXbfEAaR7D2Ujm4GAkbwcGZQMHqAMpwDoje4583uNP834`)
1445+
1446+## Support
1447+
1448+- Documentation: https://github.com/ruvnet/claude-flow
1449+- Issues: https://github.com/ruvnet/claude-flow/issues
1450+
1451+---
1452+
1453+Remember: **Claude Flow coordinates, Claude Code creates!**
1454+
1455+## Gateway-Delegated Development (meta-llm dev-bridge)
1456+
1457+For complex reasoning, architecture decisions, or hard bug-fixes, **delegate via the
1458+`metallm_delegate` MCP tool rather than solving inline.** The meta-llm gateway governs the
1459+work: it routes cheap-tier-first, escalates genuinely-hard tasks to the frontier (Fable),
1460+and meters every call — so delegation is cost-governed and preserves the main session's context.
1461+
1462+- **Default to `cognitum-auto`** — the gateway picks the tier by difficulty. Only pass an
1463+ explicit tier (`cognitum-low|mid|high`) when you must force one.
1464+- Prompt-wrapping does **not** inflate cost — the gateway normalizes host scaffolds so an
1465+ everyday sub-task still routes to the cheap tier. Trust `cognitum-auto`.
1466+- Use **`metallm_delegate`** for agentic sub-tasks needing tools/files in a working dir
1467+ (its `cwd` is sandboxed); use **`metallm_ask`** for a single-shot question — it returns
1468+ the gateway's real metered cost + resolved tier/model in-band.
1469+- Reserve the main (inline) session for orchestration, integration, and final review;
1470+ push expensive per-sub-task reasoning through the gateway.
1471+
1472+**Setup (per developer, local — never committed):** register the `metallm-dev-bridge` MCP
1473+server via a local `.mcp.json` (gitignored) and export your gateway key as `COGNITUM_DEV_KEY`
1474+in your shell. Build steps + the exact `.mcp.json` block are in the internal meta-llm
1475+dev-bridge README. **Never commit the key or an inline gateway URL.**
1476+
1477+### `ask` vs `delegate` — pick by task shape (load-bearing)
1478+
1479+**Use `metallm_ask` for single-shot facts, summaries, classification, and small code
1480+questions. Use `metallm_delegate` only when the task needs autonomous multi-step execution
1481+or isolated agent context.**
1482+
1483+Why the split is strict: `metallm_delegate` spawns a full `claude -p` sub-agent, which loads
1484+its entire harness context **even for a trivial task** — measured floor ≈ **$0.26/call**
1485+(~43k input tokens) before any real work. `metallm_ask` is a single gateway completion —
1486+measured ≈ **$0.0001** for a small query, ~2500× cheaper. So delegating casually is
1487+expensive at volume; `delegate` pays off only when offloading the sub-task's context from
1488+the main session is worth the floor. When in doubt, `ask`.
1489+
1490+Routing caveat (tracked): `metallm_ask` **auto** currently over-tiers some trivial prompts to
1491+`mid` (sonnet-5) instead of `low` — the bridge's `/v1/messages` path may miss ADR-236
1492+host-normalization (meta-llm issue #38). Forced tiers work correctly; cost impact is small
1493+per call but real at volume.
1271494
