Two files, one repository
ruvnet/ruflo ships 2 formats across 7 indexed files. The question worth asking is whether the second one says anything the first does not.
CompareAGENTS.md ↔ CLAUDE.md
| Dimension | Shared | Only in A | Only in B | Overlap |
|---|---|---|---|---|
| Sections | 1 | 57 | 59 | 1% |
| Commands | 0 | 37 | 40 | 0% |
| Section tags | 7 | 2 | 5 | 50% |
What each file covers
Sections
1 shared · 57 only in A · 59 only in B- − Claude Flow V3 - Agent Guide
- − 📢 TL;DR - READ THIS FIRST
- − Ruflo Policy-Governed Concurrent Codex Workflow
- − 🚨 CRITICAL: CODEX DOES THE WORK, CLAUDE-FLOW ORCHESTRATES
- − ❌ WRONG: Expecting claude-flow to execute tasks
- − WRONG: Waiting for claude-flow to build the API
- − Claude-flow does NOT execute code!
- − ✅ CORRECT: Codex executes, claude-flow tracks
- − 1. Tell claude-flow what you're doing (optional coordination)
- − 2. YOU (CODEX) DO THE ACTUAL WORK:
- − 3. Report to claude-flow what you did (optional)
- − The Division of Labor
- − ⛔ DON'T STOP AFTER CALLING CLAUDE-FLOW
- − ❌ WRONG Pattern (Stopping)
- − WRONG: Codex stops here and waits for something to happen
- − Nothing will happen! Claude-flow doesn't execute code!
- − ✅ CORRECT Pattern (Continue Immediately)
- − Step 1: Coordination (optional)
- − Step 2: IMMEDIATELY DO THE WORK YOURSELF - DON'T WAIT!
- − Step 3: Report what you did
- − The Rule
- − When to Use Claude-Flow Commands
- − Hello World - Correct Pattern
- − STEP 1: Optional - register with orchestrator
- − STEP 2: CODEX DOES THE WORK
- − STEP 3: Optional - report completion
- − ⚡ QUICK COMMANDS (NO DISCOVERY NEEDED)
- − Spawn N-Agent Swarm (Copy-Paste Ready)
- − 5-AGENT SWARM - Run these commands in sequence:
- − Common Swarm Patterns
- − Agent Types (Use with `--type`)
- − Task Commands
- − Memory Commands
- − 🚀 SWARM RECIPES
- − Recipe 1: Hello World Test (COMPLETE EXAMPLE)
- − ⚠️ DON'T STOP HERE - CONTINUE IMMEDIATELY TO STEP 2
- − ✅ YOU create the file
- − ✅ YOU execute it
- − Output: Hello World from Swarm!
- − Recipe 1b: 5-Agent Concurrent Hello World (COMPLETE)
- − COORDINATION (instant - creates records only)
- − ⚠️ NOW YOU DO THE ACTUAL CONCURRENT WORK:
- − REPORT (optional)
- − Recipe 1b: Hello World (Single Command Block)
- − All-in-one execution
- − Recipe 2: Feature Implementation (6 Agents)
- − Recipe 3: Bug Fix (4 Agents)
- − Recipe 4: Security Audit (3 Agents)
- − Recipe 5: V3 Full Coordination (15 Agents)
- − 📋 BEHAVIORAL RULES
- − 🎯 WHEN TO USE SWARMS
- − 🔧 CLI REFERENCE
- − Swarm Commands
- − Agent Commands
- − Hooks Commands
- − System Commands
- − 🔌 TOPOLOGIES
- + Claude Code Configuration - Ruflo V3
- + Behavioral Rules (Always Enforced)
- + Capability Brain and Governed Implementation
- + 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
- 📁 FILE ORGANIZATION
Commands
0 shared · 37 only in A · 40 only in B- − npx ruflo policy status
- − npx ruflo policy verify
- − npx ruflo metaharness flywheel status
- − npx claude-flow swarm start --objective "Build API"
- − npx claude-flow swarm init --topology hierarchical --max-agents 1
- − npx claude-flow agent spawn --type coder --name codex-worker
- − npx claude-flow memory store --key "api-created" --value "src/api.ts" --namespace results
- − npx claude-flow swarm init --topology hierarchical
- − npx claude-flow agent spawn --type coder --name worker-1
- − npx claude-flow swarm start --objective "Build hello world"
- − node hello.js
- − npx claude-flow memory store --key "result" --value "Hello World printed" --namespace results
- − npx claude-flow swarm init --topology mesh --max-agents 1
- − npx claude-flow memory store --key "hello-result" --value "printed Hello World" --namespace results
- − npx claude-flow swarm init --topology hierarchical --max-agents 8
- − npx claude-flow agent spawn --type coordinator --name coord-1
- − npx claude-flow agent spawn --type coder --name coder-1
- − npx claude-flow agent spawn --type coder --name coder-2
- − npx claude-flow agent spawn --type tester --name tester-1
- − npx claude-flow agent spawn --type reviewer --name reviewer-1
- − npx claude-flow swarm start --objective "Your task here" --strategy development
- − npx claude-flow swarm init --topology mesh --max-agents 5 && \
- − npx claude-flow agent spawn --type coder --name hello-main && \
- − node /tmp/hello-swarm.js && \
- − npx claude-flow memory store --key "hello-world-result" --value "Executed: Hello World from Swarm!" --namespace results
- − npx claude-flow swarm init --topology hierarchical --max-agents 5
- − npx claude-flow agent spawn --type coder --name "worker-$i"
- − npx claude-flow memory store --key "concurrent-result" --value "5 workers completed" --namespace results
- − npx claude-flow swarm start --objective "Print hello world" --strategy development && \
- − npx claude-flow memory store --key "hello-world-result" --value "Success" --namespace results
- − npx claude-flow agent spawn --type coordinator --name lead
- − npx claude-flow agent spawn --type architect --name arch
- − npx claude-flow agent spawn --type coder --name impl-1
- − npx claude-flow agent spawn --type coder --name impl-2
- − npx claude-flow agent spawn --type tester --name test
- − npx claude-flow agent spawn --type reviewer --name review
- − npx claude-flow swarm start --objective "Implement [feature]" --strategy development
- + 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 run build
- + npm dist-tag add @claude-flow/cli@3.7.1 alpha
Section tags
7 shared · 2 only in A · 5 only in B- − test
- − types
- + setup
- + lint-format
- + architecture
- + testing-strategy
- + dependencies
- build
- code-style
- security
- api
- performance
- do-not
- agent-behaviour
Line diff
ruvnet/ruflo · AGENTS.md
@@ −1 @@
1# Claude Flow V3 - Agent Guide
2
3> **For OpenAI Codex CLI** - Agentic AI Foundation standard
4> Skills: `$skill-name` | Config: `.agents/config.toml`
5
6---
7
8## 📢 TL;DR - READ THIS FIRST
9
10```
11╔═══════════════════════════════════════════════════════════════════════════╗
12║ 1. claude-flow = LEDGER (tracks state, stores memory, coordinates) ║
13║ 2. Codex = EXECUTOR (writes code, runs commands, creates files) ║
14║ 3. NEVER stop after calling claude-flow - IMMEDIATELY continue working ║
15║ 4. If you need something BUILT/EXECUTED, YOU do it, not claude-flow ║
16║ 5. ALWAYS search memory BEFORE starting: memory search --query "task" ║
17║ 6. ALWAYS store patterns AFTER success: memory store --namespace patterns║
18╚═══════════════════════════════════════════════════════════════════════════╝
19```
20
21**Workflow (Use MCP Tools):**
221. `memory_search(query="task keywords")` → LEARN from past patterns (score > 0.7 = use it)
232. `swarm_init(topology="hierarchical")` → coordination record (instant)
243. **YOU write the code / run the commands** ← THIS IS WHERE WORK HAPPENS
254. `memory_store(key="pattern-x", value="what worked", namespace="patterns")` → REMEMBER for next time
26
27---
28
29## Ruflo Policy-Governed Concurrent Codex Workflow
30
31Ruflo is the coordination ledger and policy decision point. Codex agents are
32the executors. Coordination records do not write code or run tests.
33
34Use `guidance_brain({ mode: "recommend", task: "..." })` to select Ruflo
35capabilities from the live MCP registry. A registered tool is not necessarily
36configured, reachable, healthy, or authorized. If it is unavailable, continue
37with compatible guidance tools, CLI discovery, and repository instructions.
38
391. Recall relevant AgentDB memory and ADRs.
402. Inspect source, runtime, dependencies, policy, and health.
413. Route to the smallest capable topology, agents, skills, and tools.
424. Plan acceptance criteria, safety envelope, ownership, and validation.
435. Execute with Codex workers in isolated scopes; Ruflo records coordination.
446. Test focused, regression, and failure paths.
457. Validate types, security, policy, compatibility, and artifact integrity.
468. Benchmark a source-bound candidate against a source-bound baseline.
479. Optimize only measured bottlenecks without weakening safety.
4810. Bind claims and evidence into exact source/build receipts.
4911. Reconcile handoffs and disclose unresolved limitations.
5012. Publish only through a separately authorized release gate.
51
52Hard invariants:
53
54- Never run two writers in one worktree.
55- Delegation may only reduce tools, servers, namespaces, network, spend,
56 concurrency, expiry, and depth.
57- Policy denial cancels dependent work before side effects.
58- MetaHarness may evaluate candidates concurrently, but only ADR-322A may
59 promote them and MetaHarness may never expand its own SafetyEnvelope.
60- Do not commit, push, merge, release, or remove worktrees unless authorized.
61- Existing installations migrate in `legacy` policy mode; use `observe` before
62 switching to `enforce`.
63
64Repository harness integration:
65
66- If tracked repository instructions define a collaboration harness, start its
67 session only after assigning an isolated worktree.
68- Inspect existing claims, acquire exact paths/resources/ports, renew leases,
69 check acknowledged inbox messages at integration boundaries, and release ownership on
70 handoff or exit.
71- A repository lease coordinates ownership; it does not grant authorization.
72 Protected work still requires the ADR-324/325 action capability and current
73 fencing epoch.
74- In-memory reference adapters demonstrate semantics; they are not distributed,
75 restart-durable release authorities.
76- Heartbeats and lease expiry establish liveness; a PID is diagnostic only.
77- `HEAD` alone is not an exact source-state identity in a dirty worktree.
78 Release evidence must bind a clean commit or an immutable snapshot of tracked
79 and untracked changes.
80
81Useful checks:
82
83```bash
84npx ruflo policy status
85npx ruflo policy verify
86npx ruflo metaharness flywheel status
87```
88
89Repository release contract:
90
91- The stable public train is exactly `@claude-flow/cli`, `claude-flow`, and
92 `ruflo`; internal `@claude-flow/*` components are bundled and are not part of
93 a normal standalone publish.
94- Publish from a clean, reviewed source state in that order.
95- Only the CLI publish receives the helper-signing configuration from
96 `ruv-dev`; use the existing authenticated npm session for publication.
97- Run `node scripts/audit-umbrella-version-lockstep.mjs`, verify all three
98 registry versions, and align `latest`, `alpha`, and `v3alpha`.
99
100---
101
102## 🚨 CRITICAL: CODEX DOES THE WORK, CLAUDE-FLOW ORCHESTRATES
103
104```
105┌─────────────────────────────────────────────────────────────┐
106│ CLAUDE-FLOW = ORCHESTRATOR (tracks state, coordinates) │
107│ CODEX = WORKER (writes code, runs commands, implements) │
108└─────────────────────────────────────────────────────────────┘
109```
110
111### ❌ WRONG: Expecting claude-flow to execute tasks
112```bash
113npx claude-flow swarm start --objective "Build API"
114# WRONG: Waiting for claude-flow to build the API
115# Claude-flow does NOT execute code!
116```
117
118### ✅ CORRECT: Codex executes, claude-flow tracks
119```bash
120# 1. Tell claude-flow what you're doing (optional coordination)
121npx claude-flow swarm init --topology hierarchical --max-agents 1
122npx claude-flow agent spawn --type coder --name codex-worker
123
124# 2. YOU (CODEX) DO THE ACTUAL WORK:
125mkdir -p src
126cat > src/api.ts << 'EOF'
127export function hello() { return "Hello World"; }
128EOF
129
130# 3. Report to claude-flow what you did (optional)
131npx claude-flow memory store --key "api-created" --value "src/api.ts" --namespace results
132```
133
134### The Division of Labor
135
136| Component | Role | Examples |
137|-----------|------|----------|
138| **CODEX** | EXECUTES | Write files, run tests, create code, shell commands |
139| **claude-flow** | ORCHESTRATES | Track agents, store memory, coordinate tasks |
140
141---
142
143## ⛔ DON'T STOP AFTER CALLING CLAUDE-FLOW
144
145```
146┌─────────────────────────────────────────────────────────────────────────┐
147│ ❌ WRONG: Call claude-flow → STOP → Wait for results │
148│ ✅ RIGHT: Call claude-flow → IMMEDIATELY continue → YOU do the work │
149└─────────────────────────────────────────────────────────────────────────┘
150```
151
152### ❌ WRONG Pattern (Stopping)
153```bash
154npx claude-flow swarm init --topology hierarchical
155npx claude-flow agent spawn --type coder --name worker-1
156npx claude-flow swarm start --objective "Build hello world"
157# WRONG: Codex stops here and waits for something to happen
158# Nothing will happen! Claude-flow doesn't execute code!
159```
160
161### ✅ CORRECT Pattern (Continue Immediately)
162```bash
163# Step 1: Coordination (optional)
164npx claude-flow swarm init --topology hierarchical
165npx claude-flow agent spawn --type coder --name worker-1
166
167# Step 2: IMMEDIATELY DO THE WORK YOURSELF - DON'T WAIT!
168echo 'console.log("Hello World!");' > hello.js
169node hello.js
170
171# Step 3: Report what you did
172npx claude-flow memory store --key "result" --value "Hello World printed" --namespace results
173```
174
175### The Rule
176**After ANY claude-flow command, IMMEDIATELY continue with your own work.**
177
178Claude-flow commands return instantly. They create coordination RECORDS only.
179You must ALWAYS follow up with YOUR OWN execution.
180
181| After This... | IMMEDIATELY Do This... |
182|---------------|----------------------|
183| `swarm init` | Start writing code |
184| `agent spawn` | Continue implementation |
185| `task create` | Execute the task yourself |
186| `swarm start` | Begin actual work |
187
188---
189
190### When to Use Claude-Flow Commands
191
192| Use Case | Claude-Flow Command | Then Codex Does |
193|----------|---------------------|-----------------|
194| Track progress | `memory store --key "step1" --value "done"` | Continue to next step |
195| Multi-step tasks | `task create --description "step 2"` | Execute step 2 |
196| Store results | `memory store --key "output" --value "..."` | Move on |
197| Coordinate | `swarm init` | Start working |
198
199### Hello World - Correct Pattern
200
201```bash
202# STEP 1: Optional - register with orchestrator
203npx claude-flow swarm init --topology mesh --max-agents 1
204
205# STEP 2: CODEX DOES THE WORK
206echo 'console.log("Hello World!");' > hello.js
207node hello.js
208
209# STEP 3: Optional - report completion
210npx claude-flow memory store --key "hello-result" --value "printed Hello World" --namespace results
211```
212
213**REMEMBER: If you need something DONE, YOU do it. Claude-flow just tracks.**
214
215---
216
217## ⚡ QUICK COMMANDS (NO DISCOVERY NEEDED)
218
219### Spawn N-Agent Swarm (Copy-Paste Ready)
220
221```bash
222# 5-AGENT SWARM - Run these commands in sequence:
223npx claude-flow swarm init --topology hierarchical --max-agents 8
224npx claude-flow agent spawn --type coordinator --name coord-1
225npx claude-flow agent spawn --type coder --name coder-1
226npx claude-flow agent spawn --type coder --name coder-2
227npx claude-flow agent spawn --type tester --name tester-1
228npx claude-flow agent spawn --type reviewer --name reviewer-1
229npx claude-flow swarm start --objective "Your task here" --strategy development
230```
231
232### Common Swarm Patterns
233
234| Task | Exact Command |
235|------|---------------|
236| Init hierarchical swarm | `npx claude-flow swarm init --topology hierarchical --max-agents 8` |
237| Init mesh swarm | `npx claude-flow swarm init --topology mesh --max-agents 5` |
238| Init V3 mode (15 agents) | `npx claude-flow swarm init --v3-mode` |
239| Spawn coder | `npx claude-flow agent spawn --type coder --name coder-1` |
240| Spawn tester | `npx claude-flow agent spawn --type tester --name tester-1` |
241| Spawn coordinator | `npx claude-flow agent spawn --type coordinator --name coord-1` |
242| Spawn architect | `npx claude-flow agent spawn --type architect --name arch-1` |
243| Spawn reviewer | `npx claude-flow agent spawn --type reviewer --name rev-1` |
244| Spawn researcher | `npx claude-flow agent spawn --type researcher --name res-1` |
245| Start swarm | `npx claude-flow swarm start --objective "task" --strategy development` |
246| Check swarm status | `npx claude-flow swarm status` |
247| List agents | `npx claude-flow agent list` |
248| Stop swarm | `npx claude-flow swarm stop` |
249
250### Agent Types (Use with `--type`)
251
252| Type | Purpose |
253|------|---------|
254| `coordinator` | Orchestrates other agents |
255| `coder` | Writes code |
256| `tester` | Writes tests |
257| `reviewer` | Reviews code |
258| `architect` | Designs systems |
259| `researcher` | Analyzes requirements |
260| `security-architect` | Security design |
261| `performance-engineer` | Optimization |
262
263### Task Commands
264
265| Action | Command |
266|--------|---------|
267| Create task | `npx claude-flow task create --type implementation --description "desc"` |
268| List tasks | `npx claude-flow task list` |
269| Assign task | `npx claude-flow task assign TASK_ID --agent AGENT_NAME` |
270| Task status | `npx claude-flow task status TASK_ID` |
271| Cancel task | `npx claude-flow task cancel TASK_ID` |
272
273### Memory Commands
274
275| Action | Command |
276|--------|---------|
277| Store | `npx claude-flow memory store --key "key" --value "value" --namespace patterns` |
278| Search | `npx claude-flow memory search --query "search terms"` |
279| List | `npx claude-flow memory list --namespace patterns` |
280| Retrieve | `npx claude-flow memory retrieve --key "key"` |
281
282---
283
284## 🚀 SWARM RECIPES
285
286### Recipe 1: Hello World Test (COMPLETE EXAMPLE)
287
288**Step 1: Setup coordination** (returns instantly - don't stop!)
289```bash
290npx claude-flow swarm init --topology mesh --max-agents 5
291npx claude-flow agent spawn --type coder --name hello-main
292# ⚠️ DON'T STOP HERE - CONTINUE IMMEDIATELY TO STEP 2
293```
294
295**Step 2: YOU (Codex) execute the task** (THIS IS THE REAL WORK)
296```bash
297# ✅ YOU create the file
298echo 'console.log("Hello World from Swarm!");' > /tmp/hello-swarm.js
299
300# ✅ YOU execute it
301node /tmp/hello-swarm.js
302# Output: Hello World from Swarm!
303```
304
305**Step 3: Report completion** (optional - store results)
306```bash
307npx claude-flow memory store --key "hello-world-result" --value "Executed: Hello World from Swarm!" --namespace results
308```
309
310### Recipe 1b: 5-Agent Concurrent Hello World (COMPLETE)
311```bash
312# COORDINATION (instant - creates records only)
313npx claude-flow swarm init --topology hierarchical --max-agents 5
314for i in 1 2 3 4 5; do
315 npx claude-flow agent spawn --type coder --name "worker-$i"
316done
317
318# ⚠️ NOW YOU DO THE ACTUAL CONCURRENT WORK:
319for i in 1 2 3 4 5; do
320 (echo "Worker $i: Hello World!" && sleep 0.$i) &
321done
322wait
323echo "All 5 workers completed!"
324
325# REPORT (optional)
326npx claude-flow memory store --key "concurrent-result" --value "5 workers completed" --namespace results
327```
328
329### Recipe 1b: Hello World (Single Command Block)
330```bash
331# All-in-one execution
332npx claude-flow swarm init --topology mesh --max-agents 5 && \
333npx claude-flow agent spawn --type coder --name hello-main && \
334npx claude-flow swarm start --objective "Print hello world" --strategy development && \
335echo 'console.log("Hello World from Swarm!");' > /tmp/hello-swarm.js && \
336node /tmp/hello-swarm.js && \
337npx claude-flow memory store --key "hello-world-result" --value "Success" --namespace results
338```
339
340### Recipe 2: Feature Implementation (6 Agents)
341```bash
342npx claude-flow swarm init --topology hierarchical --max-agents 8
343npx claude-flow agent spawn --type coordinator --name lead
344npx claude-flow agent spawn --type architect --name arch
345npx claude-flow agent spawn --type coder --name impl-1
346npx claude-flow agent spawn --type coder --name impl-2
347npx claude-flow agent spawn --type tester --name test
348npx claude-flow agent spawn --type reviewer --name review
349npx claude-flow swarm start --objective "Implement [feature]" --strategy development
350```
351
352### Recipe 3: Bug Fix (4 Agents)
353```bash
354npx claude-flow swarm init --topology hierarchical --max-agents 4
355npx claude-flow agent spawn --type coordinator --name lead
356npx claude-flow agent spawn --type researcher --name debug
357npx claude-flow agent spawn --type coder --name fix
358npx claude-flow agent spawn --type tester --name verify
359npx claude-flow swarm start --objective "Fix [bug]" --strategy development
360```
361
362### Recipe 4: Security Audit (3 Agents)
363```bash
364npx claude-flow swarm init --topology hierarchical --max-agents 4
365npx claude-flow agent spawn --type coordinator --name lead
366npx claude-flow agent spawn --type security-architect --name audit
367npx claude-flow agent spawn --type reviewer --name review
368npx claude-flow swarm start --objective "Security audit" --strategy development
369```
370
371### Recipe 5: V3 Full Coordination (15 Agents)
372```bash
373npx claude-flow swarm init --v3-mode
374npx claude-flow swarm coordinate --agents 15
375```
376
377---
378
379## 📋 BEHAVIORAL RULES
380
381- **YOU (CODEX) execute tasks** - claude-flow only orchestrates
382- Do what is asked; nothing more, nothing less
383- NEVER create files unless absolutely necessary
384- ALWAYS prefer editing existing files
385- NEVER save to root folder
386- NEVER commit secrets or .env files
387- ALWAYS read a file before editing it
388- NEVER wait for claude-flow to "do work" - it doesn't execute, YOU do
389- Use claude-flow commands to TRACK progress, not to EXECUTE tasks
390
391## 📁 FILE ORGANIZATION
392
393| Directory | Purpose |
394|-----------|---------|
395| `/src` | Source code |
396| `/tests` | Test files |
397| `/docs` | Documentation |
398| `/config` | Configuration |
399| `/scripts` | Utility scripts |
400
401## 🎯 WHEN TO USE SWARMS
402
403**USE SWARM:**
404- Multiple files (3+)
405- New feature implementation
406- Cross-module refactoring
407- API changes with tests
408- Security-related changes
409- Performance optimization
410
411**SKIP SWARM:**
412- Single file edits
413- Simple bug fixes (1-2 lines)
414- Documentation updates
415- Configuration changes
416
417---
418
419## 🔧 CLI REFERENCE
420
421### Swarm Commands
422```bash
423npx claude-flow swarm init [--topology TYPE] [--max-agents N] [--v3-mode]
424npx claude-flow swarm start --objective "task" --strategy [development|research]
425npx claude-flow swarm status [SWARM_ID]
426npx claude-flow swarm stop [SWARM_ID]
427npx claude-flow swarm scale --count N
428npx claude-flow swarm coordinate --agents N
429```
430
431### Agent Commands
432```bash
433npx claude-flow agent spawn --type TYPE --name NAME
434npx claude-flow agent list [--filter active|idle|busy]
435npx claude-flow agent status AGENT_ID
436npx claude-flow agent stop AGENT_ID
437npx claude-flow agent metrics [AGENT_ID]
438npx claude-flow agent health
439npx claude-flow agent logs AGENT_ID
440```
441
442### Task Commands
443```bash
444npx claude-flow task create --type TYPE --description "desc"
445npx claude-flow task list [--all]
446npx claude-flow task status TASK_ID
447npx claude-flow task assign TASK_ID --agent AGENT_NAME
448npx claude-flow task cancel TASK_ID
449npx claude-flow task retry TASK_ID
450```
451
452### Memory Commands
453```bash
454npx claude-flow memory store --key KEY --value VALUE [--namespace NS]
455npx claude-flow memory search --query "terms" [--namespace NS]
456npx claude-flow memory list [--namespace NS]
457npx claude-flow memory retrieve --key KEY [--namespace NS]
458npx claude-flow memory init [--force]
459```
460
461### Hooks Commands
462```bash
463npx claude-flow hooks pre-task --description "task"
464npx claude-flow hooks post-task --task-id ID --success true
465npx claude-flow hooks route --task "task"
466npx claude-flow hooks session-start --session-id ID
467npx claude-flow hooks session-end --export-metrics true
468npx claude-flow hooks worker list
469npx claude-flow hooks worker dispatch --trigger audit
470```
471
472### System Commands
473```bash
474npx claude-flow init [--wizard] [--codex] [--full]
475npx claude-flow daemon start
476npx claude-flow daemon stop
477npx claude-flow daemon status
478npx claude-flow doctor [--fix]
479npx claude-flow status
480npx claude-flow mcp start
481```
482
483---
484
485## 🔌 TOPOLOGIES
486
487| Topology | Use Case | Command Flag |
488|----------|----------|--------------|
489| `hierarchical` | Coordinated teams, anti-drift | `--topology hierarchical` |
490| `mesh` | Peer-to-peer, equal agents | `--topology mesh` |
491| `hierarchical-mesh` | Hybrid (recommended for V3) | `--topology hierarchical-mesh` |
492| `ring` | Sequential processing | `--topology ring` |
493| `star` | Central coordinator | `--topology star` |
494| `adaptive` | Dynamic switching | `--topology adaptive` |
495
496## 🤖 AGENT TYPES
497
498### Core
499`coordinator`, `coder`, `tester`, `reviewer`, `architect`, `researcher`
500
501### Specialized
502`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`
503
504### Swarm Coordination
505`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`
506
507### Consensus
508`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`
509
510---
511
512## ⚙️ CONFIGURATION
513
514### Default Swarm Config
515- Topology: `hierarchical`
516- Max Agents: 8
517- Strategy: `specialized`
518- Consensus: `raft`
519- Memory: `hybrid`
520
521### Environment Variables
522```bash
523CLAUDE_FLOW_CONFIG=./claude-flow.config.json
524CLAUDE_FLOW_LOG_LEVEL=info
525CLAUDE_FLOW_MEMORY_BACKEND=hybrid
526```
527
528---
529
530## 🔗 SKILLS
531
532Invoke with `$skill-name`:
533
534| Skill | Purpose |
535|-------|---------|
536| `$swarm-orchestration` | Multi-agent coordination |
537| `$memory-management` | Pattern storage/retrieval |
538| `$sparc-methodology` | Structured development |
539| `$security-audit` | Security scanning |
540| `$performance-analysis` | Profiling |
541| `$github-automation` | CI/CD management |
542| `$hive-mind` | Byzantine consensus |
543| `$neural-training` | Pattern learning |
544
545---
546
547---
548
549## 🔌 MCP INTEGRATION (Learning & Coordination)
550
551Codex doesn't have native hooks like Claude Code, but uses **MCP (Model Context Protocol)** for learning and coordination.
552
553### MCP Auto-Registration
554
555When you run `npx claude-flow init --codex`, the MCP server is **automatically registered** with Codex.
556
557```bash
558# Verify MCP is registered:
559codex mcp list
560
561# Expected output:
562# Name Command Args Status
563# claude-flow npx claude-flow mcp start enabled
564
565# If not present, add manually:
566codex mcp add claude-flow -- npx claude-flow mcp start
567```
568
569### Test MCP Connection
570```bash
571# Test MCP server starts correctly:
572npx claude-flow mcp start --test
573```
574
575### MCP Tools Available
576Once added, Codex can use these tools via MCP:
577
578**Coordination:**
579| Tool | Purpose |
580|------|---------|
581| `swarm_init` | Initialize swarm (topology, maxAgents) |
582| `swarm_status` | Check swarm state |
583| `agent_spawn` | Register agent roles |
584| `agent_status` | Check agent state |
585| `task_orchestrate` | Coordinate multi-agent tasks |
586
587**Learning & Memory (USE THESE!):**
588| Tool | Purpose | When |
589|------|---------|------|
590| `memory_search` | Semantic vector search | BEFORE every task |
591| `memory_store` | Store patterns with embeddings | AFTER success |
592| `memory_retrieve` | Get by exact key | When key is known |
593| `neural_train` | Train on patterns | Periodic improvement |
594| `neural_status` | Check learning state | Debugging |
595
596**Hive Mind (Advanced):**
597| Tool | Purpose |
598|------|---------|
599| `hive-mind_init` | Byzantine consensus swarm |
600| `hive-mind_spawn` | Spawn hive workers |
601| `hive-mind_broadcast` | Message all workers |
602
603### Self-Learning via MCP Tools (PREFERRED)
604
605Use MCP tools directly - faster than CLI commands:
606
607**BEFORE starting any task - SEARCH for patterns:**
608```
609Use tool: memory_search
610 query: "keywords related to your task"
611 namespace: "patterns"
612```
613
614**AFTER completing successfully - STORE the pattern:**
615```
616Use tool: memory_store
617 key: "pattern-[descriptive-name]"
618 value: "What worked: approach, code patterns, gotchas"
619 namespace: "patterns"
620```
621
622### MCP Learning Workflow (Use This!)
623
624```
6251. LEARN: memory_search(query="task keywords", namespace="patterns")
626 → If score > 0.7, USE that pattern
627
6282. COORDINATE: swarm_init(topology="hierarchical")
629 → agent_spawn(type="coder", name="worker-1")
630
6313. EXECUTE: YOU write the code, run commands, create files
632
6334. REMEMBER: memory_store(key="pattern-x", value="what worked", namespace="patterns")
634```
635
636### MCP Tools for Learning
637
638| Tool | Purpose | When to Use |
639|------|---------|-------------|
640| `memory_search` | Find similar past patterns | BEFORE starting any task |
641| `memory_store` | Save successful patterns | AFTER completing a task |
642| `memory_retrieve` | Get specific pattern by key | When you know the exact key |
643| `neural_train` | Train on successful patterns | After multiple successes |
644
645### Example: Learning-Enabled Task
646
647```
648STEP 1 - LEARN:
649Use tool: memory_search
650 query: "validation utility function"
651 namespace: "patterns"
652
653→ Found: pattern-email-validator (score: 0.82)
654→ Use this pattern as reference!
655
656STEP 2 - COORDINATE:
657Use tool: swarm_init with topology="hierarchical", maxAgents=3
658
659STEP 3 - EXECUTE:
660YOU create the files:
661 echo 'export function validate(x) { ... }' > /tmp/validator.js
662 node --test /tmp/validator.js
663
664STEP 4 - REMEMBER:
665Use tool: memory_store
666 key: "pattern-phone-validator"
667 value: "Phone validation: regex /^\+?[\d\s-]{10,}$/, normalize first, test edge cases"
668 namespace: "patterns"
669```
670
671### Vector Search Tips
672- Searches are SEMANTIC (meaning-based, not just keywords)
673- Score > 0.7 = strong match, use that pattern
674- Score 0.5-0.7 = partial match, adapt as needed
675- Store DETAILED values for better future retrieval
676
677### CLI Fallback (if MCP unavailable)
678```bash
679npx claude-flow memory search --query "keywords" --namespace patterns
680npx claude-flow memory store --key "pattern-x" --value "what worked" --namespace patterns
681```
682
683### Coordination via MCP
684
685When claude-flow is added as MCP server, Codex can call tools directly:
686```
687Use tool: swarm_init with topology="hierarchical"
688Use tool: memory_store with key="result" value="success"
689```
690
691### config.toml MCP Setup
692```toml
693# ~/.codex/config.toml
694[mcp_servers.claude-flow]
695command = "npx"
696args = ["claude-flow", "mcp", "start"]
697enabled = true
698```
699
700---
701
702## 📚 SUPPORT
703
704- Docs: https://github.com/ruvnet/claude-flow
705- Issues: https://github.com/ruvnet/claude-flow/issues
706
707**Remember: Codex executes, claude-flow orchestrates!**
708
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 Flow V3 - Agent Guide
1+# Claude Code Configuration - Ruflo V3
22
3−> **For OpenAI Codex CLI** - Agentic AI Foundation standard
4−> Skills: `$skill-name` | Config: `.agents/config.toml`
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.
56
6−---
7+## Behavioral Rules (Always Enforced)
78
8−## 📢 TL;DR - READ THIS FIRST
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
917
10−```
11−╔═══════════════════════════════════════════════════════════════════════════╗
12−║ 1. claude-flow = LEDGER (tracks state, stores memory, coordinates) ║
13−║ 2. Codex = EXECUTOR (writes code, runs commands, creates files) ║
14−║ 3. NEVER stop after calling claude-flow - IMMEDIATELY continue working ║
15−║ 4. If you need something BUILT/EXECUTED, YOU do it, not claude-flow ║
16−║ 5. ALWAYS search memory BEFORE starting: memory search --query "task" ║
17−║ 6. ALWAYS store patterns AFTER success: memory store --namespace patterns║
18−╚═══════════════════════════════════════════════════════════════════════════╝
19−```
18+## Capability Brain and Governed Implementation
2019
21−**Workflow (Use MCP Tools):**
22−1. `memory_search(query="task keywords")` → LEARN from past patterns (score > 0.7 = use it)
23−2. `swarm_init(topology="hierarchical")` → coordination record (instant)
24−3. **YOU write the code / run the commands** ← THIS IS WHERE WORK HAPPENS
25−4. `memory_store(key="pattern-x", value="what worked", namespace="patterns")` → REMEMBER for next time
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.
2623
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+
2782 ---
2883
29−## Ruflo Policy-Governed Concurrent Codex Workflow
84+## Swarm Orchestration
3085
31−Ruflo is the coordination ledger and policy decision point. Codex agents are
32−the executors. Coordination records do not write code or run tests.
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
3389
34−Use `guidance_brain({ mode: "recommend", task: "..." })` to select Ruflo
35−capabilities from the live MCP registry. A registered tool is not necessarily
36−configured, reachable, healthy, or authorized. If it is unavailable, continue
37−with compatible guidance tools, CLI discovery, and repository instructions.
90+### MCP + Task Tool in SAME Message
3891
39−1. Recall relevant AgentDB memory and ADRs.
40−2. Inspect source, runtime, dependencies, policy, and health.
41−3. Route to the smallest capable topology, agents, skills, and tools.
42−4. Plan acceptance criteria, safety envelope, ownership, and validation.
43−5. Execute with Codex workers in isolated scopes; Ruflo records coordination.
44−6. Test focused, regression, and failure paths.
45−7. Validate types, security, policy, compatibility, and artifact integrity.
46−8. Benchmark a source-bound candidate against a source-bound baseline.
47−9. Optimize only measured bottlenecks without weakening safety.
48−10. Bind claims and evidence into exact source/build receipts.
49−11. Reconcile handoffs and disclose unresolved limitations.
50−12. Publish only through a separately authorized release gate.
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
5194
52−Hard invariants:
95+### 3-Tier Model Routing (ADR-026, ADR-143)
5396
54−- Never run two writers in one worktree.
55−- Delegation may only reduce tools, servers, namespaces, network, spend,
56− concurrency, expiry, and depth.
57−- Policy denial cancels dependent work before side effects.
58−- MetaHarness may evaluate candidates concurrently, but only ADR-322A may
59− promote them and MetaHarness may never expand its own SafetyEnvelope.
60−- Do not commit, push, merge, release, or remove worktrees unless authorized.
61−- Existing installations migrate in `legacy` policy mode; use `observe` before
62− switching to `enforce`.
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%) |
63102
64−Repository harness integration:
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
65107
66−- If tracked repository instructions define a collaboration harness, start its
67− session only after assigning an isolated worktree.
68−- Inspect existing claims, acquire exact paths/resources/ports, renew leases,
69− check acknowledged inbox messages at integration boundaries, and release ownership on
70− handoff or exit.
71−- A repository lease coordinates ownership; it does not grant authorization.
72− Protected work still requires the ADR-324/325 action capability and current
73− fencing epoch.
74−- In-memory reference adapters demonstrate semantics; they are not distributed,
75− restart-durable release authorities.
76−- Heartbeats and lease expiry establish liveness; a PID is diagnostic only.
77−- `HEAD` alone is not an exact source-state identity in a dirty worktree.
78− Release evidence must bind a clean commit or an immutable snapshot of tracked
79− and untracked changes.
108+## Swarm Configuration & Anti-Drift
80109
81−Useful checks:
110+### Anti-Drift Coding Swarm (PREFERRED DEFAULT)
82111
83−```bash
84−npx ruflo policy status
85−npx ruflo policy verify
86−npx ruflo metaharness flywheel status
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+})
87126 ```
88127
89−Repository release contract:
128+## Dual-Mode Collaboration (Claude Code + Codex)
90129
91−- The stable public train is exactly `@claude-flow/cli`, `claude-flow`, and
92− `ruflo`; internal `@claude-flow/*` components are bundled and are not part of
93− a normal standalone publish.
94−- Publish from a clean, reviewed source state in that order.
95−- Only the CLI publish receives the helper-signing configuration from
96− `ruv-dev`; use the existing authenticated npm session for publication.
97−- Run `node scripts/audit-umbrella-version-lockstep.mjs`, verify all three
98− registry versions, and align `latest`, `alpha`, and `v3alpha`.
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.
99131
100−---
132+### Why Dual-Mode?
101133
102−## 🚨 CRITICAL: CODEX DOES THE WORK, CLAUDE-FLOW ORCHESTRATES
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 |
103140
104−```
105−┌─────────────────────────────────────────────────────────────┐
106−│ CLAUDE-FLOW = ORCHESTRATOR (tracks state, coordinates) │
107−│ CODEX = WORKER (writes code, runs commands, implements) │
108−└─────────────────────────────────────────────────────────────┘
109−```
141+### Dual-Mode Swarm Protocol
110142
111−### ❌ WRONG: Expecting claude-flow to execute tasks
112−```bash
113−npx claude-flow swarm start --objective "Build API"
114−# WRONG: Waiting for claude-flow to build the API
115−# Claude-flow does NOT execute code!
116−```
143+For complex tasks, spawn both Claude and Codex workers in parallel:
117144
118−### ✅ CORRECT: Codex executes, claude-flow tracks
119−```bash
120−# 1. Tell claude-flow what you're doing (optional coordination)
121−npx claude-flow swarm init --topology hierarchical --max-agents 1
122−npx claude-flow agent spawn --type coder --name codex-worker
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+})
123152
124−# 2. YOU (CODEX) DO THE ACTUAL WORK:
125−mkdir -p src
126−cat > src/api.ts << 'EOF'
127−export function hello() { return "Hello World"; }
128−EOF
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")
129158
130−# 3. Report to claude-flow what you did (optional)
131−npx claude-flow memory store --key "api-created" --value "src/api.ts" --namespace results
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]'")
132166 ```
133167
134−### The Division of Labor
168+### Collaboration Templates (Pre-Built Pipelines)
135169
136−| Component | Role | Examples |
137−|-----------|------|----------|
138−| **CODEX** | EXECUTES | Write files, run tests, create code, shell commands |
139−| **claude-flow** | ORCHESTRATES | Track agents, store memory, coordinate tasks |
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 |
140176
141−---
177+### Dual-Mode CLI Commands
142178
143−## ⛔ DON'T STOP AFTER CALLING CLAUDE-FLOW
179+```bash
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"
144184
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
145198 ```
146−┌─────────────────────────────────────────────────────────────────────────┐
147−│ ❌ WRONG: Call claude-flow → STOP → Wait for results │
148−│ ✅ RIGHT: Call claude-flow → IMMEDIATELY continue → YOU do the work │
149−└─────────────────────────────────────────────────────────────────────────┘
150−```
151199
152−### ❌ WRONG Pattern (Stopping)
200+### Shared Memory Coordination
201+
202+All workers share state via the `collaboration` namespace:
203+
153204 ```bash
154−npx claude-flow swarm init --topology hierarchical
155−npx claude-flow agent spawn --type coder --name worker-1
156−npx claude-flow swarm start --objective "Build hello world"
157−# WRONG: Codex stops here and waits for something to happen
158−# Nothing will happen! Claude-flow doesn't execute code!
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"
159213 ```
160214
161−### ✅ CORRECT Pattern (Continue Immediately)
215+### Cross-Platform Learning
216+
217+Both platforms learn from each other's outputs:
218+
162219 ```bash
163−# Step 1: Coordination (optional)
164−npx claude-flow swarm init --topology hierarchical
165−npx claude-flow agent spawn --type coder --name worker-1
220+# After successful collaboration, train patterns
221+npx claude-flow@v3alpha hooks post-task --task-id "dual-[id]" --success true --train-neural true
166222
167−# Step 2: IMMEDIATELY DO THE WORK YOURSELF - DON'T WAIT!
168−echo 'console.log("Hello World!");' > hello.js
169−node hello.js
223+# Store successful collaboration patterns
224+npx claude-flow@v3alpha memory store --namespace patterns --key "dual-mode-[pattern]" --value "[what worked]"
170225
171−# Step 3: Report what you did
172−npx claude-flow memory store --key "result" --value "Hello World printed" --namespace results
226+# Transfer learnings to both platforms
227+npx claude-flow@v3alpha hooks transfer store --pattern "dual-collab-success"
173228 ```
174229
175−### The Rule
176−**After ANY claude-flow command, IMMEDIATELY continue with your own work.**
230+### Worker Dependency Levels
177231
178−Claude-flow commands return instantly. They create coordination RECORDS only.
179−You must ALWAYS follow up with YOUR OWN execution.
232+Workers execute in dependency order:
180233
181−| After This... | IMMEDIATELY Do This... |
182−|---------------|----------------------|
183−| `swarm init` | Start writing code |
184−| `agent spawn` | Continue implementation |
185−| `task create` | Execute the task yourself |
186−| `swarm start` | Begin actual work |
234+```
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
239+```
187240
188−---
241+### Platform Strengths
189242
190−### When to Use Claude-Flow Commands
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 |
191251
192−| Use Case | Claude-Flow Command | Then Codex Does |
193−|----------|---------------------|-----------------|
194−| Track progress | `memory store --key "step1" --value "done"` | Continue to next step |
195−| Multi-step tasks | `task create --description "step 2"` | Execute step 2 |
196−| Store results | `memory store --key "output" --value "..."` | Move on |
197−| Coordinate | `swarm init` | Start working |
252+### Programmatic API
198253
199−### Hello World - Correct Pattern
254+```typescript
255+import { DualModeOrchestrator, CollaborationTemplates } from '@claude-flow/codex';
200256
201−```bash
202−# STEP 1: Optional - register with orchestrator
203−npx claude-flow swarm init --topology mesh --max-agents 1
257+const orchestrator = new DualModeOrchestrator({
258+ namespace: 'my-feature',
259+ memoryBackend: 'hybrid'
260+});
204261
205−# STEP 2: CODEX DOES THE WORK
206−echo 'console.log("Hello World!");' > hello.js
207−node hello.js
262+// Use pre-built template
263+const workers = CollaborationTemplates.featureDevelopment('Add OAuth login');
208264
209−# STEP 3: Optional - report completion
210−npx claude-flow memory store --key "hello-result" --value "printed Hello World" --namespace results
265+// Run collaboration
266+const results = await orchestrator.runCollaboration(workers, 'Implement OAuth feature');
267+
268+// Access shared memory
269+const designDocs = await orchestrator.getMemory('design-decisions');
211270 ```
212271
213−**REMEMBER: If you need something DONE, YOU do it. Claude-flow just tracks.**
214−
215272 ---
216273
217−## ⚡ QUICK COMMANDS (NO DISCOVERY NEEDED)
274+## Swarm Protocols & Routing
218275
219−### Spawn N-Agent Swarm (Copy-Paste Ready)
276+### Auto-Start Swarm Protocol
220277
221−```bash
222−# 5-AGENT SWARM - Run these commands in sequence:
223−npx claude-flow swarm init --topology hierarchical --max-agents 8
224−npx claude-flow agent spawn --type coordinator --name coord-1
225−npx claude-flow agent spawn --type coder --name coder-1
226−npx claude-flow agent spawn --type coder --name coder-2
227−npx claude-flow agent spawn --type tester --name tester-1
228−npx claude-flow agent spawn --type reviewer --name reviewer-1
229−npx claude-flow swarm start --objective "Your task here" --strategy development
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
230325 ```
231326
232−### Common Swarm Patterns
327+### Agent Routing (Anti-Drift)
233328
234−| Task | Exact Command |
235−|------|---------------|
236−| Init hierarchical swarm | `npx claude-flow swarm init --topology hierarchical --max-agents 8` |
237−| Init mesh swarm | `npx claude-flow swarm init --topology mesh --max-agents 5` |
238−| Init V3 mode (15 agents) | `npx claude-flow swarm init --v3-mode` |
239−| Spawn coder | `npx claude-flow agent spawn --type coder --name coder-1` |
240−| Spawn tester | `npx claude-flow agent spawn --type tester --name tester-1` |
241−| Spawn coordinator | `npx claude-flow agent spawn --type coordinator --name coord-1` |
242−| Spawn architect | `npx claude-flow agent spawn --type architect --name arch-1` |
243−| Spawn reviewer | `npx claude-flow agent spawn --type reviewer --name rev-1` |
244−| Spawn researcher | `npx claude-flow agent spawn --type researcher --name res-1` |
245−| Start swarm | `npx claude-flow swarm start --objective "task" --strategy development` |
246−| Check swarm status | `npx claude-flow swarm status` |
247−| List agents | `npx claude-flow agent list` |
248−| Stop swarm | `npx claude-flow swarm stop` |
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 |
249338
250−### Agent Types (Use with `--type`)
339+**Codes 1-11: hierarchical/specialized (anti-drift). Code 13: mesh/balanced**
251340
252−| Type | Purpose |
253−|------|---------|
254−| `coordinator` | Orchestrates other agents |
255−| `coder` | Writes code |
256−| `tester` | Writes tests |
257−| `reviewer` | Reviews code |
258−| `architect` | Designs systems |
259−| `researcher` | Analyzes requirements |
260−| `security-architect` | Security design |
261−| `performance-engineer` | Optimization |
341+### Task Complexity Detection
262342
263−### Task Commands
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
264351
265−| Action | Command |
266−|--------|---------|
267−| Create task | `npx claude-flow task create --type implementation --description "desc"` |
268−| List tasks | `npx claude-flow task list` |
269−| Assign task | `npx claude-flow task assign TASK_ID --agent AGENT_NAME` |
270−| Task status | `npx claude-flow task status TASK_ID` |
271−| Cancel task | `npx claude-flow task cancel TASK_ID` |
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
272358
273−### Memory Commands
359+## Project Configuration
274360
275−| Action | Command |
276−|--------|---------|
277−| Store | `npx claude-flow memory store --key "key" --value "value" --namespace patterns` |
278−| Search | `npx claude-flow memory search --query "search terms"` |
279−| List | `npx claude-flow memory list --namespace patterns` |
280−| Retrieve | `npx claude-flow memory retrieve --key "key"` |
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)
281369
282−---
370+## V3 CLI Commands (26 Commands, 140+ Subcommands)
283371
284−## 🚀 SWARM RECIPES
372+### Core Commands
285373
286−### Recipe 1: Hello World Test (COMPLETE EXAMPLE)
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 |
287389
288−**Step 1: Setup coordination** (returns instantly - don't stop!)
289−```bash
290−npx claude-flow swarm init --topology mesh --max-agents 5
291−npx claude-flow agent spawn --type coder --name hello-main
292−# ⚠️ DON'T STOP HERE - CONTINUE IMMEDIATELY TO STEP 2
293−```
390+### Advanced Commands
294391
295−**Step 2: YOU (Codex) execute the task** (THIS IS THE REAL WORK)
296−```bash
297−# ✅ YOU create the file
298−echo 'console.log("Hello World from Swarm!");' > /tmp/hello-swarm.js
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) |
299407
300−# ✅ YOU execute it
301−node /tmp/hello-swarm.js
302−# Output: Hello World from Swarm!
303−```
408+### Quick CLI Examples
304409
305−**Step 3: Report completion** (optional - store results)
306410 ```bash
307−npx claude-flow memory store --key "hello-world-result" --value "Executed: Hello World from Swarm!" --namespace results
308−```
411+# Initialize project
412+npx claude-flow@v3alpha init --wizard
309413
310−### Recipe 1b: 5-Agent Concurrent Hello World (COMPLETE)
311−```bash
312−# COORDINATION (instant - creates records only)
313−npx claude-flow swarm init --topology hierarchical --max-agents 5
314−for i in 1 2 3 4 5; do
315− npx claude-flow agent spawn --type coder --name "worker-$i"
316−done
414+# Start daemon with background workers
415+npx claude-flow@v3alpha daemon start
317416
318−# ⚠️ NOW YOU DO THE ACTUAL CONCURRENT WORK:
319−for i in 1 2 3 4 5; do
320− (echo "Worker $i: Hello World!" && sleep 0.$i) &
321−done
322−wait
323−echo "All 5 workers completed!"
417+# Spawn an agent
418+npx claude-flow@v3alpha agent spawn -t coder --name my-coder
324419
325−# REPORT (optional)
326−npx claude-flow memory store --key "concurrent-result" --value "5 workers completed" --namespace results
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
327434 ```
328435
329−### Recipe 1b: Hello World (Single Command Block)
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+
330442 ```bash
331−# All-in-one execution
332−npx claude-flow swarm init --topology mesh --max-agents 5 && \
333−npx claude-flow agent spawn --type coder --name hello-main && \
334−npx claude-flow swarm start --objective "Print hello world" --strategy development && \
335−echo 'console.log("Hello World from Swarm!");' > /tmp/hello-swarm.js && \
336−node /tmp/hello-swarm.js && \
337−npx claude-flow memory store --key "hello-world-result" --value "Success" --namespace results
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/"
338462 ```
339463
340−### Recipe 2: Feature Implementation (6 Agents)
464+### Parallel Background Execution
465+
341466 ```bash
342−npx claude-flow swarm init --topology hierarchical --max-agents 8
343−npx claude-flow agent spawn --type coordinator --name lead
344−npx claude-flow agent spawn --type architect --name arch
345−npx claude-flow agent spawn --type coder --name impl-1
346−npx claude-flow agent spawn --type coder --name impl-2
347−npx claude-flow agent spawn --type tester --name test
348−npx claude-flow agent spawn --type reviewer --name review
349−npx claude-flow swarm start --objective "Implement [feature]" --strategy development
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"
350479 ```
351480
352−### Recipe 3: Bug Fix (4 Agents)
481+### Session Continuation
482+
353483 ```bash
354−npx claude-flow swarm init --topology hierarchical --max-agents 4
355−npx claude-flow agent spawn --type coordinator --name lead
356−npx claude-flow agent spawn --type researcher --name debug
357−npx claude-flow agent spawn --type coder --name fix
358−npx claude-flow agent spawn --type tester --name verify
359−npx claude-flow swarm start --objective "Fix [bug]" --strategy development
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"
360491 ```
361492
362−### Recipe 4: Security Audit (3 Agents)
363−```bash
364−npx claude-flow swarm init --topology hierarchical --max-agents 4
365−npx claude-flow agent spawn --type coordinator --name lead
366−npx claude-flow agent spawn --type security-architect --name audit
367−npx claude-flow agent spawn --type reviewer --name review
368−npx claude-flow swarm start --objective "Security audit" --strategy development
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);
369539 ```
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% |
370546
371−### Recipe 5: V3 Full Coordination (15 Agents)
372−```bash
373−npx claude-flow swarm init --v3-mode
374−npx claude-flow swarm coordinate --agents 15
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+
375574 ```
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+```
376582
377−---
583+### Core Principle: Named Agents + SendMessage
378584
379−## 📋 BEHAVIORAL RULES
585+Every agent MUST have a `name` so it's addressable. Communication happens via `SendMessage`, not polling or shared memory.
380586
381−- **YOU (CODEX) execute tasks** - claude-flow only orchestrates
382−- Do what is asked; nothing more, nothing less
383−- NEVER create files unless absolutely necessary
384−- ALWAYS prefer editing existing files
385−- NEVER save to root folder
386−- NEVER commit secrets or .env files
387−- ALWAYS read a file before editing it
388−- NEVER wait for claude-flow to "do work" - it doesn't execute, YOU do
389−- Use claude-flow commands to TRACK progress, not to EXECUTE tasks
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+})
390607
391−## 📁 FILE ORGANIZATION
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+```
392615
393−| Directory | Purpose |
394−|-----------|---------|
395−| `/src` | Source code |
396−| `/tests` | Test files |
397−| `/docs` | Documentation |
398−| `/config` | Configuration |
399−| `/scripts` | Utility scripts |
616+### SendMessage Protocol
400617
401−## 🎯 WHEN TO USE SWARMS
618+```javascript
619+// Lead → Teammate: assign work
620+SendMessage({ to: "developer", summary: "Implement auth", message: "Build OAuth2 flow..." })
402621
403−**USE SWARM:**
404−- Multiple files (3+)
405−- New feature implementation
406−- Cross-module refactoring
407−- API changes with tests
408−- Security-related changes
409−- Performance optimization
622+// Lead → Teammate: redirect priorities
623+SendMessage({ to: "developer", summary: "Prioritize auth", message: "Auth endpoint is blocking tester, do it first." })
410624
411−**SKIP SWARM:**
412−- Single file edits
413−- Simple bug fixes (1-2 lines)
414−- Documentation updates
415−- Configuration changes
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." })
416627
417−---
628+// Lead → Teammate: graceful shutdown
629+SendMessage({ to: "developer", message: { type: "shutdown_request" } })
630+```
418631
419−## 🔧 CLI REFERENCE
632+### Coordination Patterns
420633
421−### Swarm Commands
422−```bash
423−npx claude-flow swarm init [--topology TYPE] [--max-agents N] [--v3-mode]
424−npx claude-flow swarm start --objective "task" --strategy [development|research]
425−npx claude-flow swarm status [SWARM_ID]
426−npx claude-flow swarm stop [SWARM_ID]
427−npx claude-flow swarm scale --count N
428−npx claude-flow swarm coordinate --agents N
634+**Pipeline (A → B → C)** — each agent messages the next when done:
429635 ```
636+architect ──SendMessage──→ developer ──SendMessage──→ tester ──SendMessage──→ reviewer
637+```
638+Tell each agent WHO to message next in their prompt.
430639
431−### Agent Commands
432−```bash
433−npx claude-flow agent spawn --type TYPE --name NAME
434−npx claude-flow agent list [--filter active|idle|busy]
435−npx claude-flow agent status AGENT_ID
436−npx claude-flow agent stop AGENT_ID
437−npx claude-flow agent metrics [AGENT_ID]
438−npx claude-flow agent health
439−npx claude-flow agent logs AGENT_ID
640+**Fan-out / Fan-in** — lead spawns parallel agents, collects results:
440641 ```
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.
441647
442−### Task Commands
443−```bash
444−npx claude-flow task create --type TYPE --description "desc"
445−npx claude-flow task list [--all]
446−npx claude-flow task status TASK_ID
447−npx claude-flow task assign TASK_ID --agent AGENT_NAME
448−npx claude-flow task cancel TASK_ID
449−npx claude-flow task retry TASK_ID
648+**Supervisor / Worker** — lead assigns, workers report back:
450649 ```
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.
451655
452−### Memory Commands
453−```bash
454−npx claude-flow memory store --key KEY --value VALUE [--namespace NS]
455−npx claude-flow memory search --query "terms" [--namespace NS]
456−npx claude-flow memory list [--namespace NS]
457−npx claude-flow memory retrieve --key KEY [--namespace NS]
458−npx claude-flow memory init [--force]
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+})
459676 ```
460677
461−### Hooks Commands
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+
462713 ```bash
463−npx claude-flow hooks pre-task --description "task"
464−npx claude-flow hooks post-task --task-id ID --success true
465−npx claude-flow hooks route --task "task"
466−npx claude-flow hooks session-start --session-id ID
467−npx claude-flow hooks session-end --export-metrics true
468−npx claude-flow hooks worker list
469−npx claude-flow hooks worker dispatch --trigger audit
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
470716 ```
471717
472−### System Commands
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+
473759 ```bash
474−npx claude-flow init [--wizard] [--codex] [--full]
475−npx claude-flow daemon start
476−npx claude-flow daemon stop
477−npx claude-flow daemon status
478−npx claude-flow doctor [--fix]
479−npx claude-flow status
480−npx claude-flow mcp start
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
481782 ```
482783
483−---
784+## Intelligence System (RuVector)
484785
485−## 🔌 TOPOLOGIES
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)
486792
487−| Topology | Use Case | Command Flag |
488−|----------|----------|--------------|
489−| `hierarchical` | Coordinated teams, anti-drift | `--topology hierarchical` |
490−| `mesh` | Peer-to-peer, equal agents | `--topology mesh` |
491−| `hierarchical-mesh` | Hybrid (recommended for V3) | `--topology hierarchical-mesh` |
492−| `ring` | Sequential processing | `--topology ring` |
493−| `star` | Central coordinator | `--topology star` |
494−| `adaptive` | Dynamic switching | `--topology adaptive` |
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++
495798
496−## 🤖 AGENT TYPES
799+## Embeddings Package (v3.0.0-alpha.12)
497800
498−### Core
499−`coordinator`, `coder`, `tester`, `reviewer`, `architect`, `researcher`
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
500808
501−### Specialized
502−`security-architect`, `security-auditor`, `memory-specialist`, `performance-engineer`
809+## Hive-Mind Consensus
503810
504−### Swarm Coordination
505−`hierarchical-coordinator`, `mesh-coordinator`, `adaptive-coordinator`
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
506816
507−### Consensus
508−`byzantine-coordinator`, `raft-manager`, `gossip-coordinator`
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
509823
510−---
824+## V3 Performance Targets
511825
512−## ⚙️ CONFIGURATION
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".
513827
514−### Default Swarm Config
515−- Topology: `hierarchical`
516−- Max Agents: 8
517−- Strategy: `specialized`
518−- Consensus: `raft`
519−- Memory: `hybrid`
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 |
520838
521−### Environment Variables
839+## Environment Variables
840+
522841 ```bash
842+# Configuration
523843 CLAUDE_FLOW_CONFIG=./claude-flow.config.json
524844 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
525857 CLAUDE_FLOW_MEMORY_BACKEND=hybrid
858+CLAUDE_FLOW_MEMORY_PATH=./data/memory
526859 ```
527860
528−---
861+## Doctor Health Checks
529862
530−## 🔗 SKILLS
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
531874
532−Invoke with `$skill-name`:
875+## Quick Setup
533876
534−| Skill | Purpose |
535−|-------|---------|
536−| `$swarm-orchestration` | Multi-agent coordination |
537−| `$memory-management` | Pattern storage/retrieval |
538−| `$sparc-methodology` | Structured development |
539−| `$security-audit` | Security scanning |
540−| `$performance-analysis` | Profiling |
541−| `$github-automation` | CI/CD management |
542−| `$hive-mind` | Byzantine consensus |
543−| `$neural-training` | Pattern learning |
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
544882
545−---
883+# Start daemon
884+npx claude-flow@v3alpha daemon start
546885
547−---
886+# Run doctor
887+npx claude-flow@v3alpha doctor --fix
888+```
548889
549−## 🔌 MCP INTEGRATION (Learning & Coordination)
890+## Claude Code vs MCP Tools
550891
551−Codex doesn't have native hooks like Claude Code, but uses **MCP (Model Context Protocol)** for learning and coordination.
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
552899
553−### MCP Auto-Registration
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
554907
555−When you run `npx claude-flow init --codex`, the MCP server is **automatically registered** with Codex.
908+- Keep MCP for coordination strategy only — use Claude Code's Task tool for real execution
556909
557−```bash
558−# Verify MCP is registered:
559−codex mcp list
910+## Claude Code ↔ AgentDB Memory Bridge
560911
561−# Expected output:
562−# Name Command Args Status
563−# claude-flow npx claude-flow mcp start enabled
912+Claude Code's auto-memory (`~/.claude/projects/*/memory/*.md`) is bridged to AgentDB with ONNX vector embeddings for semantic search.
564913
565−# If not present, add manually:
566−codex mcp add claude-flow -- npx claude-flow mcp start
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
567932 ```
568933
569−### Test MCP Connection
934+### Unified Search
935+
936+Search across both Claude Code memories and AgentDB entries:
937+
570938 ```bash
571−# Test MCP server starts correctly:
572−npx claude-flow mcp start --test
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
573943 ```
574944
575−### MCP Tools Available
576−Once added, Codex can use these tools via MCP:
945+### Intelligence Pipeline
577946
578−**Coordination:**
579−| Tool | Purpose |
580−|------|---------|
581−| `swarm_init` | Initialize swarm (topology, maxAgents) |
582−| `swarm_status` | Check swarm state |
583−| `agent_spawn` | Register agent roles |
584−| `agent_status` | Check agent state |
585−| `task_orchestrate` | Coordinate multi-agent tasks |
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 |
586953
587−**Learning & Memory (USE THESE!):**
588−| Tool | Purpose | When |
589−|------|---------|------|
590−| `memory_search` | Semantic vector search | BEFORE every task |
591−| `memory_store` | Store patterns with embeddings | AFTER success |
592−| `memory_retrieve` | Get by exact key | When key is known |
593−| `neural_train` | Train on patterns | Periodic improvement |
594−| `neural_status` | Check learning state | Debugging |
954+## Publishing to npm
595955
596−**Hive Mind (Advanced):**
597−| Tool | Purpose |
598−|------|---------|
599−| `hive-mind_init` | Byzantine consensus swarm |
600−| `hive-mind_spawn` | Spawn hive workers |
601−| `hive-mind_broadcast` | Message all workers |
956+### Versioning policy (stable releases — alpha series ended at 3.7.0-alpha.81, 2026-05-23)
602957
603−### Self-Learning via MCP Tools (PREFERRED)
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.
604965
605−Use MCP tools directly - faster than CLI commands:
966+### Publishing Rules
606967
607−**BEFORE starting any task - SEARCH for patterns:**
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
6081019 ```
609−Use tool: memory_search
610− query: "keywords related to your task"
611− namespace: "patterns"
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
6121051 ```
6131052
614−**AFTER completing successfully - STORE the pattern:**
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
6151126 ```
616−Use tool: memory_store
617− key: "pattern-[descriptive-name]"
618− value: "What worked: approach, code patterns, gotchas"
619− namespace: "patterns"
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
6201136 ```
6211137
622−### MCP Learning Workflow (Use This!)
1138+### All Tags That Must Be Updated
6231139
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
6241166 ```
625−1. LEARN: memory_search(query="task keywords", namespace="patterns")
626− → If score > 0.7, USE that pattern
6271167
628−2. COORDINATE: swarm_init(topology="hierarchical")
629− → agent_spawn(type="coder", name="worker-1")
1168+## Plugin Registry Maintenance (IPFS/Pinata)
6301169
631−3. EXECUTE: YOU write the code, run commands, create files
1170+The plugin registry is stored on IPFS via Pinata for decentralized, immutable distribution.
6321171
633−4. REMEMBER: memory_store(key="pattern-x", value="what worked", namespace="patterns")
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
6341183 ```
6351184
636−### MCP Tools for Learning
1185+## Plugin Registry Operations
6371186
638−| Tool | Purpose | When to Use |
639−|------|---------|-------------|
640−| `memory_search` | Find similar past patterns | BEFORE starting any task |
641−| `memory_store` | Save successful patterns | AFTER completing a task |
642−| `memory_retrieve` | Get specific pattern by key | When you know the exact key |
643−| `neural_train` | Train on successful patterns | After multiple successes |
1187+### Adding a New Plugin to Registry
6441188
645−### Example: Learning-Enabled Task
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+```
6461193
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+}
6471220 ```
648−STEP 1 - LEARN:
649−Use tool: memory_search
650− query: "validation utility function"
651− namespace: "patterns"
6521221
653−→ Found: pattern-email-validator (score: 0.82)
654−→ Use this pattern as reference!
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`
6551227
656−STEP 2 - COORDINATE:
657−Use tool: swarm_init with topology="hierarchical", maxAgents=3
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-)
6581232
659−STEP 3 - EXECUTE:
660−YOU create the files:
661− echo 'export function validate(x) { ... }' > /tmp/validator.js
662− node --test /tmp/validator.js
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+```
6631239
664−STEP 4 - REMEMBER:
665−Use tool: memory_store
666− key: "pattern-phone-validator"
667− value: "Phone validation: regex /^\+?[\d\s-]{10,}$/, normalize first, test edge cases"
668− namespace: "patterns"
1240+5. **Update discovery.ts** with new CID:
1241+```typescript
1242+export const LIVE_REGISTRY_CID = 'NEW_CID_FROM_PINATA';
6691243 ```
6701244
671−### Vector Search Tips
672−- Searches are SEMANTIC (meaning-based, not just keywords)
673−- Score > 0.7 = strong match, use that pattern
674−- Score 0.5-0.7 = partial match, adapt as needed
675−- Store DETAILED values for better future retrieval
1245+6. **Also update demo registry** in discovery.ts `demoPluginRegistry` for offline fallback
6761246
677−### CLI Fallback (if MCP unavailable)
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
6781254 ```bash
679−npx claude-flow memory search --query "keywords" --namespace patterns
680−npx claude-flow memory store --key "pattern-x" --value "what worked" --namespace patterns
1255+# Verify new registry is accessible
1256+curl -s "https://gateway.pinata.cloud/ipfs/{NEW_CID}" | jq '.totalPlugins'
6811257 ```
6821258
683−### Coordination via MCP
1259+## MetaHarness Integration (ADR-150)
6841260
685−When claude-flow is added as MCP server, Codex can call tools directly:
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
6861350 ```
687−Use tool: swarm_init with topology="hierarchical"
688−Use tool: memory_store with key="result" value="success"
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
6891363 ```
6901364
691−### config.toml MCP Setup
692−```toml
693−# ~/.codex/config.toml
694−[mcp_servers.claude-flow]
695−command = "npx"
696−args = ["claude-flow", "mcp", "start"]
697−enabled = true
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
6981394 ```
6991395
700−---
1396+### Core Plugins
7011397
702−## 📚 SUPPORT
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 |
7031406
704−- Docs: https://github.com/ruvnet/claude-flow
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
7051449 - Issues: https://github.com/ruvnet/claude-flow/issues
7061450
707−**Remember: Codex executes, claude-flow orchestrates!**
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.
7081494
