diff --git a/v3/@claude-flow/cli/__tests__/__snapshots__/init-single-host-claudemd-snapshot-2638.test.ts.snap b/v3/@claude-flow/cli/__tests__/__snapshots__/init-single-host-claudemd-snapshot-2638.test.ts.snap new file mode 100644 index 0000000000..5e9bd25d78 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/__snapshots__/init-single-host-claudemd-snapshot-2638.test.ts.snap @@ -0,0 +1,4714 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`single-host CLAUDE.md is unchanged (#2638) > executeInit writes the same CLAUDE.md > default preset 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > executeInit writes the same CLAUDE.md > full preset 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > executeInit writes the same CLAUDE.md > minimal preset 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: mesh (anti-drift) +- **Max Agents**: 5 +- **Memory**: memory +- **HNSW**: Disabled +- **Neural**: Disabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(default, full) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Hooks + +| Hook | Purpose | +|------|---------| +| \`pre-task\` / \`post-task\` | Task lifecycle + learning | +| \`pre-edit\` / \`post-edit\` | File editing + neural training | +| \`session-start\` / \`session-end\` | Session persistence | +| \`route\` | Route to optimal agent | +| \`intelligence\` | Pattern learning (SONA) | +| \`worker\` | Background worker dispatch | + +\`\`\`bash +npx @claude-flow/cli@latest hooks pre-task --description "[task]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true +npx @claude-flow/cli@latest hooks session-start --session-id "[id]" +npx @claude-flow/cli@latest hooks route --task "[task]" +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Intelligence (SONA + HNSW) + +Pipeline: **RETRIEVE** (vector search) → **JUDGE** (success/failure) → **DISTILL** (extract patterns) → **CONSOLIDATE** (persist) + +- **ONNX Embeddings**: all-MiniLM-L6-v2, 384-dim +- **HNSW**: faster than brute-force search, magnitude scales with corpus size — reproduce with \`node scripts/benchmark-intelligence.mjs --only=hnsw\` rather than a hardcoded multiplier +- **SONA**: Sub-millisecond pattern adaptation +- **Claude Bridge**: Auto-imports \`~/.claude/projects/*/memory/*.md\` into AgentDB + +## Federation + +Cross-installation agent collaboration with zero-trust security. + +\`\`\`bash +npx @claude-flow/cli@latest federation init +npx @claude-flow/cli@latest federation join wss://peer:8443 +npx @claude-flow/cli@latest federation send --to peer --type task-request --message "..." +npx @claude-flow/cli@latest federation status +\`\`\` + +- 5-tier trust: UNTRUSTED → VERIFIED → ATTESTED → TRUSTED → PRIVILEGED +- PII pipeline: 14 types auto-stripped before data leaves your node +- mTLS + ed25519 handshake, HMAC-signed envelopes +- Compliance: HIPAA, SOC2, GDPR audit modes + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## Environment + +\`\`\`bash +CLAUDE_FLOW_CONFIG=./claude-flow.config.json +CLAUDE_FLOW_LOG_LEVEL=info +CLAUDE_FLOW_MEMORY_BACKEND=hybrid +CLAUDE_FLOW_MEMORY_PATH=./data/memory +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(default, minimal) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(default, performance) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Performance + +- Always benchmark before AND after optimization +- Always profile before optimizing — never guess bottlenecks +- Use HNSW for vector search, Int8 quantization for memory reduction — measure the actual speedup/recall on your own corpus via \`node scripts/benchmark-intelligence.mjs --only=hnsw\` rather than trusting a hardcoded multiplier (recall@10 varies by corpus size — 0.99 at N=5k, 0.92 at N=20k on the reference host, dream-cycle 2026-08-30) + +\`\`\`bash +npx @claude-flow/cli@latest performance benchmark --suite all +npx @claude-flow/cli@latest performance profile --target "[component]" +\`\`\` + +Agents: \`performance-engineer\` (profiling), \`perf-analyzer\` (bottleneck detection) + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Intelligence (SONA + HNSW) + +Pipeline: **RETRIEVE** (vector search) → **JUDGE** (success/failure) → **DISTILL** (extract patterns) → **CONSOLIDATE** (persist) + +- **ONNX Embeddings**: all-MiniLM-L6-v2, 384-dim +- **HNSW**: faster than brute-force search, magnitude scales with corpus size — reproduce with \`node scripts/benchmark-intelligence.mjs --only=hnsw\` rather than a hardcoded multiplier +- **SONA**: Sub-millisecond pattern adaptation +- **Claude Bridge**: Auto-imports \`~/.claude/projects/*/memory/*.md\` into AgentDB + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(default, security) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Security + +- NEVER hardcode secrets in source — use environment variables +- Always validate input at boundaries (Zod schemas) +- Always sanitize file paths (prevent traversal) +- Always use parameterized queries (prevent injection) + +\`\`\`bash +npx @claude-flow/cli@latest security scan --depth deep +npx @claude-flow/cli@latest security audit --report +\`\`\` + +Agents: \`security-architect\` (threat modeling), \`security-auditor\` (vulnerability detection) + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(default, solo) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(default, standard) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(full, full) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Hooks + +| Hook | Purpose | +|------|---------| +| \`pre-task\` / \`post-task\` | Task lifecycle + learning | +| \`pre-edit\` / \`post-edit\` | File editing + neural training | +| \`session-start\` / \`session-end\` | Session persistence | +| \`route\` | Route to optimal agent | +| \`intelligence\` | Pattern learning (SONA) | +| \`worker\` | Background worker dispatch | + +\`\`\`bash +npx @claude-flow/cli@latest hooks pre-task --description "[task]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true +npx @claude-flow/cli@latest hooks session-start --session-id "[id]" +npx @claude-flow/cli@latest hooks route --task "[task]" +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Intelligence (SONA + HNSW) + +Pipeline: **RETRIEVE** (vector search) → **JUDGE** (success/failure) → **DISTILL** (extract patterns) → **CONSOLIDATE** (persist) + +- **ONNX Embeddings**: all-MiniLM-L6-v2, 384-dim +- **HNSW**: faster than brute-force search, magnitude scales with corpus size — reproduce with \`node scripts/benchmark-intelligence.mjs --only=hnsw\` rather than a hardcoded multiplier +- **SONA**: Sub-millisecond pattern adaptation +- **Claude Bridge**: Auto-imports \`~/.claude/projects/*/memory/*.md\` into AgentDB + +## Federation + +Cross-installation agent collaboration with zero-trust security. + +\`\`\`bash +npx @claude-flow/cli@latest federation init +npx @claude-flow/cli@latest federation join wss://peer:8443 +npx @claude-flow/cli@latest federation send --to peer --type task-request --message "..." +npx @claude-flow/cli@latest federation status +\`\`\` + +- 5-tier trust: UNTRUSTED → VERIFIED → ATTESTED → TRUSTED → PRIVILEGED +- PII pipeline: 14 types auto-stripped before data leaves your node +- mTLS + ed25519 handshake, HMAC-signed envelopes +- Compliance: HIPAA, SOC2, GDPR audit modes + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## Environment + +\`\`\`bash +CLAUDE_FLOW_CONFIG=./claude-flow.config.json +CLAUDE_FLOW_LOG_LEVEL=info +CLAUDE_FLOW_MEMORY_BACKEND=hybrid +CLAUDE_FLOW_MEMORY_PATH=./data/memory +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(full, minimal) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(full, performance) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Performance + +- Always benchmark before AND after optimization +- Always profile before optimizing — never guess bottlenecks +- Use HNSW for vector search, Int8 quantization for memory reduction — measure the actual speedup/recall on your own corpus via \`node scripts/benchmark-intelligence.mjs --only=hnsw\` rather than trusting a hardcoded multiplier (recall@10 varies by corpus size — 0.99 at N=5k, 0.92 at N=20k on the reference host, dream-cycle 2026-08-30) + +\`\`\`bash +npx @claude-flow/cli@latest performance benchmark --suite all +npx @claude-flow/cli@latest performance profile --target "[component]" +\`\`\` + +Agents: \`performance-engineer\` (profiling), \`perf-analyzer\` (bottleneck detection) + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Intelligence (SONA + HNSW) + +Pipeline: **RETRIEVE** (vector search) → **JUDGE** (success/failure) → **DISTILL** (extract patterns) → **CONSOLIDATE** (persist) + +- **ONNX Embeddings**: all-MiniLM-L6-v2, 384-dim +- **HNSW**: faster than brute-force search, magnitude scales with corpus size — reproduce with \`node scripts/benchmark-intelligence.mjs --only=hnsw\` rather than a hardcoded multiplier +- **SONA**: Sub-millisecond pattern adaptation +- **Claude Bridge**: Auto-imports \`~/.claude/projects/*/memory/*.md\` into AgentDB + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(full, security) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Security + +- NEVER hardcode secrets in source — use environment variables +- Always validate input at boundaries (Zod schemas) +- Always sanitize file paths (prevent traversal) +- Always use parameterized queries (prevent injection) + +\`\`\`bash +npx @claude-flow/cli@latest security scan --depth deep +npx @claude-flow/cli@latest security audit --report +\`\`\` + +Agents: \`security-architect\` (threat modeling), \`security-auditor\` (vulnerability detection) + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(full, solo) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(full, standard) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: hierarchical-mesh (anti-drift) +- **Max Agents**: 15 +- **Memory**: hybrid +- **HNSW**: Enabled +- **Neural**: Enabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(minimal, full) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: mesh (anti-drift) +- **Max Agents**: 5 +- **Memory**: memory +- **HNSW**: Disabled +- **Neural**: Disabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Hooks + +| Hook | Purpose | +|------|---------| +| \`pre-task\` / \`post-task\` | Task lifecycle + learning | +| \`pre-edit\` / \`post-edit\` | File editing + neural training | +| \`session-start\` / \`session-end\` | Session persistence | +| \`route\` | Route to optimal agent | +| \`intelligence\` | Pattern learning (SONA) | +| \`worker\` | Background worker dispatch | + +\`\`\`bash +npx @claude-flow/cli@latest hooks pre-task --description "[task]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true +npx @claude-flow/cli@latest hooks session-start --session-id "[id]" +npx @claude-flow/cli@latest hooks route --task "[task]" +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Intelligence (SONA + HNSW) + +Pipeline: **RETRIEVE** (vector search) → **JUDGE** (success/failure) → **DISTILL** (extract patterns) → **CONSOLIDATE** (persist) + +- **ONNX Embeddings**: all-MiniLM-L6-v2, 384-dim +- **HNSW**: faster than brute-force search, magnitude scales with corpus size — reproduce with \`node scripts/benchmark-intelligence.mjs --only=hnsw\` rather than a hardcoded multiplier +- **SONA**: Sub-millisecond pattern adaptation +- **Claude Bridge**: Auto-imports \`~/.claude/projects/*/memory/*.md\` into AgentDB + +## Federation + +Cross-installation agent collaboration with zero-trust security. + +\`\`\`bash +npx @claude-flow/cli@latest federation init +npx @claude-flow/cli@latest federation join wss://peer:8443 +npx @claude-flow/cli@latest federation send --to peer --type task-request --message "..." +npx @claude-flow/cli@latest federation status +\`\`\` + +- 5-tier trust: UNTRUSTED → VERIFIED → ATTESTED → TRUSTED → PRIVILEGED +- PII pipeline: 14 types auto-stripped before data leaves your node +- mTLS + ed25519 handshake, HMAC-signed envelopes +- Compliance: HIPAA, SOC2, GDPR audit modes + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## Environment + +\`\`\`bash +CLAUDE_FLOW_CONFIG=./claude-flow.config.json +CLAUDE_FLOW_LOG_LEVEL=info +CLAUDE_FLOW_MEMORY_BACKEND=hybrid +CLAUDE_FLOW_MEMORY_PATH=./data/memory +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(minimal, minimal) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: mesh (anti-drift) +- **Max Agents**: 5 +- **Memory**: memory +- **HNSW**: Disabled +- **Neural**: Disabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(minimal, performance) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: mesh (anti-drift) +- **Max Agents**: 5 +- **Memory**: memory +- **HNSW**: Disabled +- **Neural**: Disabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Performance + +- Always benchmark before AND after optimization +- Always profile before optimizing — never guess bottlenecks +- Use HNSW for vector search, Int8 quantization for memory reduction — measure the actual speedup/recall on your own corpus via \`node scripts/benchmark-intelligence.mjs --only=hnsw\` rather than trusting a hardcoded multiplier (recall@10 varies by corpus size — 0.99 at N=5k, 0.92 at N=20k on the reference host, dream-cycle 2026-08-30) + +\`\`\`bash +npx @claude-flow/cli@latest performance benchmark --suite all +npx @claude-flow/cli@latest performance profile --target "[component]" +\`\`\` + +Agents: \`performance-engineer\` (profiling), \`perf-analyzer\` (bottleneck detection) + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Intelligence (SONA + HNSW) + +Pipeline: **RETRIEVE** (vector search) → **JUDGE** (success/failure) → **DISTILL** (extract patterns) → **CONSOLIDATE** (persist) + +- **ONNX Embeddings**: all-MiniLM-L6-v2, 384-dim +- **HNSW**: faster than brute-force search, magnitude scales with corpus size — reproduce with \`node scripts/benchmark-intelligence.mjs --only=hnsw\` rather than a hardcoded multiplier +- **SONA**: Sub-millisecond pattern adaptation +- **Claude Bridge**: Auto-imports \`~/.claude/projects/*/memory/*.md\` into AgentDB + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(minimal, security) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: mesh (anti-drift) +- **Max Agents**: 5 +- **Memory**: memory +- **HNSW**: Disabled +- **Neural**: Disabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Security + +- NEVER hardcode secrets in source — use environment variables +- Always validate input at boundaries (Zod schemas) +- Always sanitize file paths (prevent traversal) +- Always use parameterized queries (prevent injection) + +\`\`\`bash +npx @claude-flow/cli@latest security scan --depth deep +npx @claude-flow/cli@latest security audit --report +\`\`\` + +Agents: \`security-architect\` (threat modeling), \`security-auditor\` (vulnerability detection) + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(minimal, solo) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; + +exports[`single-host CLAUDE.md is unchanged (#2638) > generateClaudeMd(minimal, standard) 1`] = ` +"# Ruflo — Claude Code Configuration + +## Rules + +- Do what has been asked; nothing more, nothing less +- NEVER create files unless absolutely necessary — prefer editing existing files +- NEVER create documentation files unless explicitly requested +- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` +- ALWAYS read a file before editing it +- NEVER commit secrets, credentials, or .env files +- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. +- Keep files under 500 lines +- Validate input at system boundaries + +## Ruflo Capability Brain & Implementation Loop + +Ruflo is the coordination ledger and policy decision point. Claude Code is the +executor: after a Ruflo coordination call, continue implementing the task. + +When it is registered, call +\`guidance_brain({ mode: "recommend", task: "..." })\` before complex Ruflo +work. Use its live registry instead of guessing tool names. Treat +\`registered\`, \`configured\`, \`reachable\`, \`healthy\`, and \`authorized\` +as separate facts. If the brain is unavailable, continue with the compatible +\`guidance_recommend\` tool, CLI discovery, and repository instructions. + +Follow the returned loop: + +1. Recall memory and ADR constraints. +2. Inspect source, runtime, dependencies, policy, and health. +3. Route to the smallest capable topology, agents, skills, and tools. +4. Plan acceptance criteria, safety envelope, ownership, and validation. +5. Execute in isolated scopes; the coding agent performs the work. +6. Test focused, regression, and failure paths. +7. Validate types, security, policy, compatibility, and artifacts. +8. Benchmark a source-bound candidate against a source-bound baseline. +9. Optimize measured bottlenecks without weakening safety. +10. Bind claims and evidence to exact source/build receipts. +11. Reconcile concurrent handoffs and disclose limitations. +12. Publish only through a separately authorized release gate. + +### Concurrency and authority + +- Never allow two writers in one worktree; give each writing agent an isolated + worktree and explicit file ownership. +- Read-only research may run concurrently and report findings to the owner. +- Only the integration owner edits shared manifests and lockfiles or reconciles + overlapping changes. +- A child may drop capabilities but cannot add tools, network, secrets, spend, + concurrency, namespaces, or delegation depth. +- A lease or claim coordinates ownership; it does not authorize a side effect. +- Darwin, Flywheel, MetaHarness, memory, and neural systems may propose or + evaluate candidates but cannot self-promote or expand their SafetyEnvelope. +- Bind tests, benchmarks, policy decisions, and release evidence to an exact + commit or immutable dirty-worktree snapshot. + +## Agent Comms (SendMessage-First Coordination) + +Named agents coordinate via \`SendMessage\`, not polling or shared state. + +\`\`\` +Lead (you) ←→ architect ←→ developer ←→ tester ←→ reviewer + (named agents message each other directly) +\`\`\` + +### Spawning a Coordinated Team + +\`\`\`javascript +// ALL agents in ONE message, each knows WHO to message next +Agent({ prompt: "Research the codebase. SendMessage findings to 'architect'.", + subagent_type: "researcher", name: "researcher", run_in_background: true }) +Agent({ prompt: "Wait for 'researcher'. Design solution. SendMessage to 'coder'.", + subagent_type: "system-architect", name: "architect", run_in_background: true }) +Agent({ prompt: "Wait for 'architect'. Implement it. SendMessage to 'tester'.", + subagent_type: "coder", name: "coder", run_in_background: true }) +Agent({ prompt: "Wait for 'coder'. Write tests. SendMessage results to 'reviewer'.", + subagent_type: "tester", name: "tester", run_in_background: true }) +Agent({ prompt: "Wait for 'tester'. Review code quality and security.", + subagent_type: "reviewer", name: "reviewer", run_in_background: true }) + +// Kick off the pipeline +SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) +\`\`\` + +### Patterns + +| Pattern | Flow | Use When | +|---------|------|----------| +| **Pipeline** | A → B → C → D | Sequential dependencies (feature dev) | +| **Fan-out** | Lead → A, B, C → Lead | Independent parallel work (research) | +| **Supervisor** | Lead ↔ workers | Ongoing coordination (complex refactor) | + +### Rules + +- ALWAYS name agents — \`name: "role"\` makes them addressable +- ALWAYS include comms instructions in prompts — who to message, what to send +- Spawn ALL agents in ONE message with \`run_in_background: true\` +- After spawning, continue independent local work; wait only when a dependency + genuinely blocks progress +- Do not poll repeatedly — agents message back or complete automatically +- Give every writing agent an isolated worktree and a non-overlapping file scope + +## Swarm & Routing + +### Config +- **Topology**: mesh (anti-drift) +- **Max Agents**: 5 +- **Memory**: memory +- **HNSW**: Disabled +- **Neural**: Disabled + +\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions + +### 3-Tier Model Routing + +| Tier | Handler | Use Cases | +|------|---------|-----------| +| 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | +| 2 | Haiku | Simple tasks, low complexity | +| 3 | Sonnet/Opus | Architecture, security, complex reasoning | + +## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\` + +## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type. + +## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\` + +## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details. + +## Setup + +\`\`\`bash +claude mcp add claude-flow -- npx -y ruflo@latest mcp start +npx ruflo@latest doctor --fix +\`\`\` + +> The background \`daemon\` is optional. It runs interval workers that each spawn +> a headless \`claude\` session, so it consumes tokens continuously. Start it only +> if you want those sweeps: \`npx ruflo@latest daemon start\` (self-stops after 12h +> by default; \`--ttl 0\` to disable, \`daemon status --all\` to audit running daemons). + +**Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash. +" +`; diff --git a/v3/@claude-flow/cli/__tests__/init-dual-native-2636-2637.test.ts b/v3/@claude-flow/cli/__tests__/init-dual-native-2636-2637.test.ts index b3db897e4c..6a752a0ac6 100644 --- a/v3/@claude-flow/cli/__tests__/init-dual-native-2636-2637.test.ts +++ b/v3/@claude-flow/cli/__tests__/init-dual-native-2636-2637.test.ts @@ -77,7 +77,7 @@ describe('native dual initialization (#2636)', () => { expect(codexMock.initialize).toHaveBeenCalledWith(expect.objectContaining({ projectPath, template: 'minimal', - dual: false, + dual: true, })); }); }); diff --git a/v3/@claude-flow/cli/__tests__/init-dual-single-source-2638.test.ts b/v3/@claude-flow/cli/__tests__/init-dual-single-source-2638.test.ts new file mode 100644 index 0000000000..b63ce9c859 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/init-dual-single-source-2638.test.ts @@ -0,0 +1,189 @@ +/** + * #2638 — `init --dual`: AGENTS.md is the single source for the shared + * sections; CLAUDE.md is `@AGENTS.md` plus Claude-only sections. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { CommandContext } from '../src/types.js'; + +// The Codex package that writes AGENTS.md: its workspace source, not the +// registry copy the CLI pins. +import { generateDualAgentsMd } from '../../codex/src/generators/dual-instructions.js'; + +const codexMock = vi.hoisted(() => ({ initialize: vi.fn() })); +vi.mock('@claude-flow/codex', () => ({ + CodexInitializer: class { + initialize = codexMock.initialize; + }, +})); + +import { initCommand } from '../src/commands/init.js'; +import { generateClaudeMd, generateDualClaudeMd, sharedSectionsForImport } from '../src/init/claudemd-generator.js'; +import { finalizeDualInstructions, writeDualClaudeMd } from '../src/init/dual-instructions.js'; +import { executeInit } from '../src/init/executor.js'; +import { DEFAULT_INIT_OPTIONS, MINIMAL_INIT_OPTIONS, type ClaudeMdTemplate, type InitOptions, type InitResult } from '../src/init/types.js'; + +const here = fileURLToPath(new URL('.', import.meta.url)); +const TEMPLATES: ClaudeMdTemplate[] = ['minimal', 'standard', 'full', 'security', 'performance', 'solo']; +const h2 = (md: string) => md.split('\n').filter((l) => /^## /.test(l)); +const importLine = (md: string) => md.split('\n').some((l) => l.trim() === '@AGENTS.md'); + +function emptyResult(): InitResult { + return { + success: true, + platform: {} as InitResult['platform'], + created: { directories: [], files: [] }, + skipped: [], + errors: [], + summary: { skillsCount: 0, commandsCount: 0, agentsCount: 0, hooksEnabled: 0 }, + }; +} + +describe('shared sections have one source (#2638)', () => { + it('the CLI mirror is byte-identical to the codex module', () => { + const canonical = readFileSync(join(here, '../../codex/src/generators/shared-instructions.ts'), 'utf-8'); + const mirror = readFileSync(join(here, '../src/init/shared-instructions.ts'), 'utf-8'); + expect(mirror).toBe(canonical); + }); + + it('the single-host CLAUDE.md contains every shared section verbatim (no drift)', () => { + const md = generateClaudeMd(DEFAULT_INIT_OPTIONS, 'standard'); + // Rules and Swarm are split around Claude-only lines, so check their shared lines. + for (const section of sharedSectionsForImport().slice(2)) expect(md).toContain(section); + }); +}); + +describe('generateDualClaudeMd (#2638)', () => { + const agents = generateDualAgentsMd({ projectName: 'demo' }); + + for (const template of TEMPLATES) { + it(`${template}: imports AGENTS.md, repeats no shared section, loses no line`, () => { + const dual = generateDualClaudeMd(DEFAULT_INIT_OPTIONS, template); + expect(importLine(dual)).toBe(true); + for (const section of sharedSectionsForImport()) expect(dual).not.toContain(section); + expect(h2(dual).filter((h) => h2(agents).includes(h))).toEqual([]); + + // Lossless: every line of the single-host file is in CLAUDE.md or AGENTS.md. + const single = generateClaudeMd(DEFAULT_INIT_OPTIONS, template); + const missing = single.split('\n') + .filter((l) => l.trim() && !/^#{1,3} /.test(l)) + .filter((l) => !dual.includes(l) && !agents.includes(l)); + expect(missing).toEqual([]); + }); + } +}); + +describe('writeDualClaudeMd + finalizeDualInstructions (#2638)', () => { + let dir: string; + const options = (): InitOptions => ({ ...structuredClone(DEFAULT_INIT_OPTIONS), targetDir: dir }); + beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'dual-2638-')); }); + afterEach(() => { rmSync(dir, { recursive: true, force: true }); }); + + it('writes the import form when CLAUDE.md does not exist', () => { + const result = emptyResult(); + writeDualClaudeMd(join(dir, 'CLAUDE.md'), options(), result); + expect(importLine(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'))).toBe(true); + expect(result.dualInstructions).toBeDefined(); + }); + + it('keeps a user-modified CLAUDE.md and says how to migrate', () => { + writeFileSync(join(dir, 'CLAUDE.md'), '# mine\n', 'utf-8'); + const result = emptyResult(); + writeDualClaudeMd(join(dir, 'CLAUDE.md'), options(), result); + expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toBe('# mine\n'); + expect(result.skipped.join('\n')).toMatch(/move your custom sections into AGENTS\.md.*@AGENTS\.md/); + expect(result.dualInstructions).toBeUndefined(); + }); + + it('converts a CLAUDE.md that init generated and nobody edited', () => { + const opts = options(); + writeFileSync(join(dir, 'CLAUDE.md'), generateClaudeMd(opts), 'utf-8'); + const result = emptyResult(); + writeDualClaudeMd(join(dir, 'CLAUDE.md'), opts, result); + expect(importLine(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'))).toBe(true); + expect(existsSync(join(dir, 'CLAUDE.md.pre-ruflo'))).toBe(false); + }); + + it('--force replaces a user CLAUDE.md after backing it up', () => { + writeFileSync(join(dir, 'CLAUDE.md'), '# mine\n', 'utf-8'); + const result = emptyResult(); + writeDualClaudeMd(join(dir, 'CLAUDE.md'), { ...options(), force: true }, result); + expect(readFileSync(join(dir, 'CLAUDE.md.pre-ruflo'), 'utf-8')).toBe('# mine\n'); + expect(importLine(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'))).toBe(true); + }); + + it('keeps the import when AGENTS.md carries the shared sections', () => { + const result = emptyResult(); + writeDualClaudeMd(join(dir, 'CLAUDE.md'), options(), result); + writeFileSync(join(dir, 'AGENTS.md'), generateDualAgentsMd({ projectName: 'demo' }), 'utf-8'); + expect(finalizeDualInstructions(dir, result).action).toBe('import'); + expect(importLine(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'))).toBe(true); + }); + + it('restores the full CLAUDE.md when AGENTS.md lacks the shared sections (old codex / failed pass)', () => { + const result = emptyResult(); + writeDualClaudeMd(join(dir, 'CLAUDE.md'), options(), result); + writeFileSync(join(dir, 'AGENTS.md'), '# Native Codex Instructions\n', 'utf-8'); + expect(finalizeDualInstructions(dir, result).action).toBe('restored'); + expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toBe(result.dualInstructions!.fullForm); + }); + + it('never touches a CLAUDE.md changed after the Claude pass', () => { + const result = emptyResult(); + writeDualClaudeMd(join(dir, 'CLAUDE.md'), options(), result); + writeFileSync(join(dir, 'CLAUDE.md'), '# edited\n', 'utf-8'); + expect(finalizeDualInstructions(dir, result).action).toBe('none'); + expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toBe('# edited\n'); + }); + + it('single-host executeInit still writes the full CLAUDE.md', async () => { + const opts = { ...structuredClone(MINIMAL_INIT_OPTIONS), targetDir: dir, skipGlobalClaudeMd: true }; + await executeInit(opts); + expect(importLine(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'))).toBe(false); + }); +}); + +describe('ruflo init --dual end to end (#2638)', () => { + let dir: string; + let configDir: string; + let saved: string | undefined; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'dual-e2e-2638-')); + configDir = mkdtempSync(join(tmpdir(), 'dual-e2e-cfg-')); + saved = process.env.CLAUDE_CONFIG_DIR; + process.env.CLAUDE_CONFIG_DIR = configDir; + codexMock.initialize.mockImplementation(async (o: Record) => { + const target = String(o.projectPath); + // Stand-in for the codex initializer: dual → the real dual AGENTS.md. + writeFileSync(join(target, 'AGENTS.md'), o.dual ? generateDualAgentsMd({ projectName: 'demo' }) : '# single\n', 'utf8'); + return { success: true, filesCreated: ['AGENTS.md'], skillsGenerated: [], warnings: [] }; + }); + }); + afterEach(() => { + vi.clearAllMocks(); + if (saved === undefined) delete process.env.CLAUDE_CONFIG_DIR; + else process.env.CLAUDE_CONFIG_DIR = saved; + rmSync(dir, { recursive: true, force: true }); + rmSync(configDir, { recursive: true, force: true }); + }); + + it('CLAUDE.md imports AGENTS.md and no section is in both files', async () => { + const ctx: CommandContext = { + args: [], + flags: { _: [], dual: true, minimal: true, global: false, 'no-signup': true, 'no-skills-sh': true }, + cwd: dir, + interactive: false, + }; + const result = await initCommand.action!(ctx); + expect(result?.success).toBe(true); + expect(codexMock.initialize).toHaveBeenCalledWith(expect.objectContaining({ dual: true })); + + const claude = readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'); + const agents = readFileSync(join(dir, 'AGENTS.md'), 'utf-8'); + expect(importLine(claude)).toBe(true); + expect(h2(claude).filter((h) => h2(agents).includes(h))).toEqual([]); + }); +}); diff --git a/v3/@claude-flow/cli/__tests__/init-single-host-claudemd-snapshot-2638.test.ts b/v3/@claude-flow/cli/__tests__/init-single-host-claudemd-snapshot-2638.test.ts new file mode 100644 index 0000000000..c1ef85a0ec --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/init-single-host-claudemd-snapshot-2638.test.ts @@ -0,0 +1,68 @@ +/** + * #2638 — single-host CLAUDE.md output must not change. + * + * Recorded on origin/main before the dual-mode single-source work. Splitting + * the section generators into shared and Claude-only parts must reproduce + * these bytes exactly for every template and preset. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { generateClaudeMd } from '../src/init/claudemd-generator.js'; +import { + DEFAULT_INIT_OPTIONS, + FULL_INIT_OPTIONS, + MINIMAL_INIT_OPTIONS, + type ClaudeMdTemplate, + type InitOptions, +} from '../src/init/types.js'; +import { executeInit } from '../src/init/executor.js'; + +const TEMPLATES: ClaudeMdTemplate[] = ['minimal', 'standard', 'full', 'security', 'performance', 'solo']; +const PRESETS: Array<[string, InitOptions]> = [ + ['default', DEFAULT_INIT_OPTIONS], + ['minimal', MINIMAL_INIT_OPTIONS], + ['full', FULL_INIT_OPTIONS], +]; + +describe('single-host CLAUDE.md is unchanged (#2638)', () => { + for (const [preset, options] of PRESETS) { + for (const template of TEMPLATES) { + it(`generateClaudeMd(${preset}, ${template})`, () => { + expect(generateClaudeMd(options, template)).toMatchSnapshot(); + }); + } + } + + describe('executeInit writes the same CLAUDE.md', () => { + let dir: string; + let configDir: string; + let savedConfigDir: string | undefined; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'claudemd-snap-')); + // Hermetic: no installed Claude Code plugins visible to init. + configDir = mkdtempSync(join(tmpdir(), 'claudemd-snap-cfg-')); + savedConfigDir = process.env.CLAUDE_CONFIG_DIR; + process.env.CLAUDE_CONFIG_DIR = configDir; + }); + afterEach(() => { + if (savedConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR; + else process.env.CLAUDE_CONFIG_DIR = savedConfigDir; + rmSync(dir, { recursive: true, force: true }); + rmSync(configDir, { recursive: true, force: true }); + }); + + for (const [preset, base] of PRESETS) { + it(`${preset} preset`, async () => { + const options: InitOptions = structuredClone(base); + options.targetDir = dir; + options.skipGlobalClaudeMd = true; + options.components = { ...options.components, helpers: false, statusline: false, settings: false }; + const result = await executeInit(options); + expect(result.success).toBe(true); + expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toMatchSnapshot(); + }); + } + }); +}); diff --git a/v3/@claude-flow/cli/src/commands/init.ts b/v3/@claude-flow/cli/src/commands/init.ts index 24e149ad5f..2eb813eadf 100644 --- a/v3/@claude-flow/cli/src/commands/init.ts +++ b/v3/@claude-flow/cli/src/commands/init.ts @@ -16,7 +16,9 @@ import { DEFAULT_INIT_OPTIONS, MINIMAL_INIT_OPTIONS, FULL_INIT_OPTIONS, + finalizeDualInstructions, type InitOptions, + type InitResult, } from '../init/index.js'; import { executeGrokInit } from '../init/grok-generator.js'; import { @@ -592,7 +594,10 @@ async function initCodexAction( if (!CodexInitializer) { spinner.stop(); output.printInfo('Fetching the stable Codex adapter for this initialization...'); - const success = runCodexInitializerCli(ctx.cwd, { template, force, dual: dualMode, codexTrust }); + // #2638: never pass --dual to a fetched adapter of unknown version — an + // older one rewrites CLAUDE.md with its own stub under --force. Without + // it, finalizeDualInstructions keeps the full CLAUDE.md. + const success = runCodexInitializerCli(ctx.cwd, { template, force, dual: false, codexTrust }); if (!success) { output.printError('Codex initialization failed while running @claude-flow/codex@latest.'); return { success: false, exitCode: 1 }; @@ -842,6 +847,11 @@ const initClaudeAction = async (ctx: CommandContext): Promise => options.skipGlobalClaudeMd = true; } + // #2638 — set by the --dual route below: CLAUDE.md imports AGENTS.md. + if (ctx.flags.instructionsSource === 'agents-md') { + options.instructionsSource = 'agents-md'; + } + const riskyMode = riskyModeFromFlags(ctx.flags); if (typeof riskyMode === 'object') { output.printError(riskyMode.error); @@ -1124,8 +1134,9 @@ const initClaudeAction = async (ctx: CommandContext): Promise => /** * Route platform initialization. Dual mode deliberately runs both native - * initializers: Claude Code first, then Codex without its compatibility - * CLAUDE.md stub so the full native Claude scaffold remains authoritative. + * initializers: Claude Code first, then Codex. #2638: AGENTS.md carries the + * shared instruction sections once and CLAUDE.md imports it (`@AGENTS.md`) + * with only the Claude-specific sections; the .claude/ scaffold is unchanged. */ const initAction = async (ctx: CommandContext): Promise => { const force = ctx.flags.force as boolean; @@ -1159,6 +1170,8 @@ const initAction = async (ctx: CommandContext): Promise => { dual: false, // The explicit Codex pass below owns Codex setup. 'no-codex-detect': true, + // #2638 — AGENTS.md owns the shared sections; CLAUDE.md imports it. + instructionsSource: 'agents-md', }, }; const claudeResult = await initClaudeAction(claudeContext); @@ -1166,12 +1179,17 @@ const initAction = async (ctx: CommandContext): Promise => { const codexResult = await initCodexAction(ctx, { codexMode: true, - // Preserve the full CLAUDE.md and .claude/ scaffold just generated. - dualMode: false, + // #2638 — dual AGENTS.md (shared + Codex-only sections). Codex leaves a + // CLAUDE.md that already imports AGENTS.md alone. + dualMode: true, force, minimal, full, }); + // Keep the @AGENTS.md import only if AGENTS.md really carries the shared + // sections; otherwise the full CLAUDE.md is written back. + const instructions = finalizeDualInstructions(ctx.cwd, claudeResult.data as InitResult | undefined); + if (instructions.action === 'restored' && instructions.message) output.printWarning(instructions.message); if (!codexResult.success) { return { ...codexResult, diff --git a/v3/@claude-flow/cli/src/init/claudemd-generator.ts b/v3/@claude-flow/cli/src/init/claudemd-generator.ts index f35bd99358..d1190a2a7f 100644 --- a/v3/@claude-flow/cli/src/init/claudemd-generator.ts +++ b/v3/@claude-flow/cli/src/init/claudemd-generator.ts @@ -7,21 +7,30 @@ */ import type { InitOptions, ClaudeMdTemplate } from './types.js'; +import { + AGENTS_MD_IMPORT, + CLAUDE_RULE_INSERT_AT, + SHARED_RULE_LINES, + SWARM_ROUTING_BODY, + sharedAgentTypes, + sharedBuildAndTest, + sharedCliQuickRef, + sharedMemoryAndLearning, +} from './shared-instructions.js'; // --- Section Generators --- +// +// #2638: sections both hosts share come from shared-instructions.ts (the +// mirror of the codex module that writes them into AGENTS.md). Everything +// left in this file is Claude-specific, or a template extra. + +/** Claude-only: the Claude Code Bash tool suggests this trailer; Codex has its own commit rule. */ +const CO_AUTHORED_BY_RULE = '- NEVER add a `Co-Authored-By` trailer to user commits unless this project\'s `.claude/settings.json` has `attribution.commit` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. `Co-Authored-By` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author.'; function behavioralRules(): string { - return `## Rules - -- Do what has been asked; nothing more, nothing less -- NEVER create files unless absolutely necessary — prefer editing existing files -- NEVER create documentation files unless explicitly requested -- NEVER save working files or tests to root — use \`/src\`, \`/tests\`, \`/docs\`, \`/config\`, \`/scripts\` -- ALWAYS read a file before editing it -- NEVER commit secrets, credentials, or .env files -- NEVER add a \`Co-Authored-By\` trailer to user commits unless this project's \`.claude/settings.json\` has \`attribution.commit\` set (#2078). The Claude Code Bash tool may suggest one in its default commit-message template — ignore it. \`Co-Authored-By\` is semantic authorship attribution under git/GitHub convention; the tool is the facilitator, not a co-author. -- Keep files under 500 lines -- Validate input at system boundaries`; + const lines = [...SHARED_RULE_LINES]; + lines.splice(CLAUDE_RULE_INSERT_AT, 0, CO_AUTHORED_BY_RULE); + return `## Rules\n\n${lines.join('\n')}`; } function policyGovernedWorkflow(): string { @@ -116,113 +125,32 @@ SendMessage({ to: "researcher", summary: "Start", message: "[task context]" }) - Give every writing agent an isolated worktree and a non-overlapping file scope`; } -function swarmConfig(options: InitOptions): string { - return `## Swarm & Routing - -### Config +function swarmRuntimeConfig(options: InitOptions): string { + return `### Config - **Topology**: ${options.runtime.topology} (anti-drift) - **Max Agents**: ${options.runtime.maxAgents} - **Memory**: ${options.runtime.memoryBackend} - **HNSW**: ${options.runtime.enableHNSW ? 'Enabled' : 'Disabled'} -- **Neural**: ${options.runtime.enableNeural ? 'Enabled' : 'Disabled'} +- **Neural**: ${options.runtime.enableNeural ? 'Enabled' : 'Disabled'}`; +} -\`\`\`bash -npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized -\`\`\` - -### Agent Routing - -| Task | Agents | Topology | -|------|--------|----------| -| Bug Fix | researcher, coder, tester | hierarchical | -| Feature | architect, coder, tester, reviewer | hierarchical | -| Refactor | architect, coder, reviewer | hierarchical | -| Performance | perf-engineer, coder | hierarchical | -| Security | security-architect, auditor | hierarchical | - -### When to Swarm -- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance -- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions - -### 3-Tier Model Routing +/** Claude-only: the tiers map onto Claude Code's Agent tool `model` choices. */ +const THREE_TIER_ROUTING = `### 3-Tier Model Routing | Tier | Handler | Use Cases | |------|---------|-----------| | 1 | Agent Booster (WASM) | Simple transforms — skip LLM, use Edit directly | | 2 | Haiku | Simple tasks, low complexity | | 3 | Sonnet/Opus | Architecture, security, complex reasoning |`; + +function swarmConfig(options: InitOptions): string { + return `## Swarm & Routing\n\n${swarmRuntimeConfig(options)}\n\n${SWARM_ROUTING_BODY}\n\n${THREE_TIER_ROUTING}`; } -function memoryAndLearning(): string { - return `## Memory & Learning - -### Before Any Task -\`\`\`bash -npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns -npx @claude-flow/cli@latest hooks route --task "[task description]" -\`\`\` - -### After Success -\`\`\`bash -npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" -npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true -\`\`\` - -### MCP Tools (use \`ToolSearch("keyword")\` to discover) - -| Category | Key Tools | -|----------|-----------| -| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | -| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | -| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | -| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | -| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | -| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | -| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | - -### Background Workers - -| Worker | When | -|--------|------| -| \`audit\` | After security changes | -| \`optimize\` | After performance work | -| \`testgaps\` | After adding features | -| \`map\` | Every 5+ file changes | -| \`document\` | After API changes | - -\`\`\`bash -npx @claude-flow/cli@latest hooks worker dispatch --trigger audit -\`\`\``; -} - -function agentTypes(): string { - return `## Agents - -**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` -**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` -**Security**: \`security-architect\`, \`security-auditor\` -**Performance**: \`performance-engineer\`, \`perf-analyzer\` -**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` -**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` - -Any string works as a custom agent type.`; -} - -function cliQuickRef(): string { - return `## CLI Quick Reference - -\`\`\`bash -npx @claude-flow/cli@latest init --wizard # Setup -npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm -npx @claude-flow/cli@latest memory search --query "" # Vector search -npx @claude-flow/cli@latest hooks route --task "" # Route to agent -npx @claude-flow/cli@latest doctor --fix # Diagnostics -npx @claude-flow/cli@latest security scan # Security scan -npx @claude-flow/cli@latest performance benchmark # Benchmarks -\`\`\` - -26 commands, 140+ subcommands. Use \`--help\` on any command for details.`; -} +const memoryAndLearning = sharedMemoryAndLearning; +const agentTypes = sharedAgentTypes; +const cliQuickRef = sharedCliQuickRef; +const buildAndTest = sharedBuildAndTest; function setupAndBoundary(): string { return `## Setup @@ -240,17 +168,6 @@ npx ruflo@latest doctor --fix **Agent tool** handles execution (agents, files, code, git). **MCP tools** handle coordination (swarm, memory, hooks). **CLI** is the same via Bash.`; } -function buildAndTest(): string { - return `## Build & Test - -- ALWAYS run tests after code changes -- ALWAYS verify build succeeds before committing - -\`\`\`bash -npm run build && npm test -\`\`\``; -} - function securitySection(): string { return `## Security @@ -433,6 +350,41 @@ export function generateMinimalClaudeMd(options: InitOptions): string { return generateClaudeMd(options, 'minimal'); } +/** The sections a CLAUDE.md that imports AGENTS.md must not repeat. */ +export function sharedSectionsForImport(): string[] { + return [ + `## Rules\n\n${SHARED_RULE_LINES.join('\n')}`, + `## Swarm & Routing\n\n${SWARM_ROUTING_BODY}`, + sharedMemoryAndLearning(), + sharedAgentTypes(), + sharedBuildAndTest(), + sharedCliQuickRef(), + ]; +} + +/** + * #2638 dual mode: CLAUDE.md imports AGENTS.md (which carries the shared + * sections) and keeps only what is Claude-specific, plus any template extras + * the shared set does not cover. Nothing here repeats a shared section. + */ +export function generateDualClaudeMd(options: InitOptions, template?: ClaudeMdTemplate): string { + const tmpl = template ?? options.runtime.claudeMdTemplate ?? 'standard'; + const sections = TEMPLATE_SECTIONS[tmpl] ?? TEMPLATE_SECTIONS.standard; + const shared = new Set(sharedSectionsForImport()); + + const body = sections.map((fn) => { + if (fn === behavioralRules) return `## Claude Code Rules\n\n${CO_AUTHORED_BY_RULE}`; + if (fn === swarmConfig) return `## Swarm Runtime & Model Routing\n\n${swarmRuntimeConfig(options)}\n\n${THREE_TIER_ROUTING}`; + const text = fn(options); + return shared.has(text) ? null : text; + }).filter((s): s is string => s !== null).join('\n\n'); + + const header = `# Ruflo — Claude Code Configuration\n\n${AGENTS_MD_IMPORT}\n\n` + + '> Shared project instructions live in `AGENTS.md`, imported above; OpenAI Codex reads the same file. ' + + 'Edit shared rules there. This file holds only Claude Code–specific guidance.\n'; + return `${header}\n${body}\n`; +} + export const CLAUDE_MD_TEMPLATES: Array<{ name: ClaudeMdTemplate; description: string }> = [ { name: 'minimal', description: 'Lean start — rules, agent comms, swarm config, CLI ref (~80 lines)' }, { name: 'standard', description: 'Recommended — adds memory, learning, agent types (~140 lines)' }, diff --git a/v3/@claude-flow/cli/src/init/dual-instructions.ts b/v3/@claude-flow/cli/src/init/dual-instructions.ts new file mode 100644 index 0000000000..cc337c13f0 --- /dev/null +++ b/v3/@claude-flow/cli/src/init/dual-instructions.ts @@ -0,0 +1,101 @@ +/** + * #2638 — dual-host instructions with one source. + * + * `init --dual` makes AGENTS.md the single source for the sections both hosts + * share. CLAUDE.md becomes Claude Code's `@AGENTS.md` import plus only the + * Claude-specific sections. Two steps: + * + * 1. writeDualClaudeMd (Claude pass) writes the import form, but only over a + * CLAUDE.md that is missing, already ours and unmodified, or --force. + * 2. finalizeDualInstructions (after the Codex pass) checks that AGENTS.md + * really carries every shared section. If it does not (Codex init failed, + * or an older @claude-flow/codex wrote the single-host AGENTS.md), the full + * single-host CLAUDE.md is written back, so nothing is lost. + */ + +import * as fs from 'fs'; +import * as path from 'path'; +import type { InitOptions, InitResult } from './types.js'; +import { generateClaudeMd, generateDualClaudeMd, sharedSectionsForImport } from './claudemd-generator.js'; +import { importsAgentsMd } from './shared-instructions.js'; + +export const DUAL_MIGRATION_HINT = + 'to share instructions with Codex, move your custom sections into AGENTS.md and replace the shared ones ' + + 'with a line `@AGENTS.md`, or re-run with --force (the current file is backed up to CLAUDE.md.pre-ruflo)'; + +function inferredTemplate(options: InitOptions) { + return (!options.components.commands && !options.components.agents) ? 'minimal' as const : undefined; +} + +function backup(claudeMdPath: string, result: InitResult): void { + const base = `${claudeMdPath}.pre-ruflo`; + const target = fs.existsSync(base) ? `${base}.${Date.now()}` : base; + fs.copyFileSync(claudeMdPath, target); + result.created.files.push(path.basename(target)); +} + +/** Claude pass of `init --dual`: write CLAUDE.md as the AGENTS.md import form when it is safe to. */ +export function writeDualClaudeMd(claudeMdPath: string, options: InitOptions, result: InitResult): void { + const template = inferredTemplate(options); + const fullForm = generateClaudeMd(options, template); + const importForm = generateDualClaudeMd(options, template); + + if (fs.existsSync(claudeMdPath)) { + const existing = fs.readFileSync(claudeMdPath, 'utf-8'); + if (existing === importForm || (importsAgentsMd(existing) && !options.force)) { + result.skipped.push('CLAUDE.md (already imports AGENTS.md)'); + return; + } + const ours = existing === fullForm; + if (!ours && !options.force) { + result.skipped.push(`CLAUDE.md (has your own content; ${DUAL_MIGRATION_HINT})`); + return; + } + if (!ours) backup(claudeMdPath, result); + } + + fs.writeFileSync(claudeMdPath, importForm, 'utf-8'); + result.created.files.push('CLAUDE.md (imports AGENTS.md)'); + result.dualInstructions = { importForm, fullForm }; +} + +export interface DualFinalizeOutcome { + /** `import`: CLAUDE.md imports AGENTS.md. `restored`: full CLAUDE.md written back. `none`: nothing to do. */ + action: 'import' | 'restored' | 'none'; + message?: string; +} + +/** + * After the Codex pass: keep the import form only when AGENTS.md carries every + * shared section verbatim. Never touches a CLAUDE.md this run did not write. + */ +export function finalizeDualInstructions(targetDir: string, claudeResult: InitResult | undefined): DualFinalizeOutcome { + const dual = claudeResult?.dualInstructions; + if (!dual) return { action: 'none' }; + + const claudeMdPath = path.join(targetDir, 'CLAUDE.md'); + let current: string | undefined; + try { + current = fs.readFileSync(claudeMdPath, 'utf-8'); + } catch { + return { action: 'none' }; + } + if (current !== dual.importForm) return { action: 'none' }; + + let agentsMd = ''; + try { + agentsMd = fs.readFileSync(path.join(targetDir, 'AGENTS.md'), 'utf-8'); + } catch { /* missing AGENTS.md: handled below */ } + + const missing = sharedSectionsForImport().filter((section) => !agentsMd.includes(section)); + if (missing.length === 0) { + return { action: 'import', message: 'CLAUDE.md imports AGENTS.md (shared sections live once, in AGENTS.md)' }; + } + + fs.writeFileSync(claudeMdPath, dual.fullForm, 'utf-8'); + return { + action: 'restored', + message: `AGENTS.md is missing ${missing.length} shared section(s) (Codex init failed, or an older @claude-flow/codex ran), ` + + 'so the full CLAUDE.md was kept instead of the @AGENTS.md import', + }; +} diff --git a/v3/@claude-flow/cli/src/init/executor.ts b/v3/@claude-flow/cli/src/init/executor.ts index 52a191b617..eb68afd53f 100644 --- a/v3/@claude-flow/cli/src/init/executor.ts +++ b/v3/@claude-flow/cli/src/init/executor.ts @@ -30,6 +30,7 @@ import { } from './helpers-generator.js'; import { getInstalledCliVersion, HELPERS_STAMP_FILE } from './helper-refresh.js'; import { generateClaudeMd } from './claudemd-generator.js'; +import { writeDualClaudeMd } from './dual-instructions.js'; import { recordMemoryPackagePath } from './memory-package-resolver.js'; import { COMMONJS_COMPANION_HELPERS, ensureCommonJsCompanions } from './helper-companions.js'; import { scanSettingsForRisk, formatRiskFindingsAsWarnings, RISKY_SETTINGS_HINT, type RiskySettingsMode } from './settings-risk-scanner.js'; @@ -2304,7 +2305,9 @@ async function writeClaudeMd( ): Promise { const claudeMdPath = path.join(targetDir, 'CLAUDE.md'); - if (fs.existsSync(claudeMdPath) && !options.force) { + if (options.instructionsSource === 'agents-md') { + writeDualClaudeMd(claudeMdPath, options, result); + } else if (fs.existsSync(claudeMdPath) && !options.force) { result.skipped.push('CLAUDE.md'); } else { // #2208: if overwriting an existing CLAUDE.md (force mode), back it up first so diff --git a/v3/@claude-flow/cli/src/init/index.ts b/v3/@claude-flow/cli/src/init/index.ts index 1ae4436133..c7934c38db 100644 --- a/v3/@claude-flow/cli/src/init/index.ts +++ b/v3/@claude-flow/cli/src/init/index.ts @@ -55,9 +55,13 @@ export { export { generateClaudeMd, generateMinimalClaudeMd, + generateDualClaudeMd, CLAUDE_MD_TEMPLATES, } from './claudemd-generator.js'; +// #2638 dual-host instructions (AGENTS.md is the single source) +export { finalizeDualInstructions, type DualFinalizeOutcome } from './dual-instructions.js'; + // Main executor export { executeInit, executeUpgrade, executeUpgradeWithMissing, default } from './executor.js'; export type { UpgradeResult } from './executor.js'; diff --git a/v3/@claude-flow/cli/src/init/shared-instructions.ts b/v3/@claude-flow/cli/src/init/shared-instructions.ts new file mode 100644 index 0000000000..30ef53b08a --- /dev/null +++ b/v3/@claude-flow/cli/src/init/shared-instructions.ts @@ -0,0 +1,165 @@ +/** + * Shared Ruflo instruction sections (#2638). + * + * The host-neutral half of the project instructions: the text both Claude + * Code and Codex should read. In a dual project AGENTS.md carries these + * sections once, and CLAUDE.md pulls them in with Claude Code's `@AGENTS.md` + * import, adding only Claude-specific guidance. + * + * Canonical copy: v3/@claude-flow/codex/src/generators/shared-instructions.ts + * Mirror: v3/@claude-flow/cli/src/init/shared-instructions.ts + * + * The two files must stay byte-identical (a CLI test compares them). The CLI + * keeps a mirror instead of importing it because it pins a published + * @claude-flow/codex release, which cannot see unreleased exports; once the + * CLI pins a codex release that ships this module, the mirror can go. + * + * Pure: no imports, no I/O. + */ + +/** Rules both hosts follow. The Claude-only commit-trailer rule is kept by the CLI. */ +export const SHARED_RULE_LINES: readonly string[] = [ + '- Do what has been asked; nothing more, nothing less', + '- NEVER create files unless absolutely necessary — prefer editing existing files', + '- NEVER create documentation files unless explicitly requested', + '- NEVER save working files or tests to root — use `/src`, `/tests`, `/docs`, `/config`, `/scripts`', + '- ALWAYS read a file before editing it', + '- NEVER commit secrets, credentials, or .env files', + '- Keep files under 500 lines', + '- Validate input at system boundaries', +]; + +/** Position of the Claude-only commit-trailer rule inside the single-host Rules list. */ +export const CLAUDE_RULE_INSERT_AT = 6; + +export function sharedRules(): string { + return `## Rules\n\n${SHARED_RULE_LINES.join('\n')}`; +} + +/** Swarm body shared by both hosts: init command, routing table, when to swarm. */ +export const SWARM_ROUTING_BODY = `\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions`; + +export function sharedSwarmRouting(): string { + return `## Swarm & Routing\n\n${SWARM_ROUTING_BODY}`; +} + +export function sharedMemoryAndLearning(): string { + return `## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\``; +} + +export function sharedAgentTypes(): string { + return `## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type.`; +} + +export function sharedBuildAndTest(): string { + return `## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\``; +} + +export function sharedCliQuickRef(): string { + return `## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details.`; +} + +/** + * Every shared section, in order. AGENTS.md (dual mode) writes all of them; + * a CLAUDE.md that imports AGENTS.md must not repeat any of them. + */ +export function generateSharedInstructions(): string[] { + return [ + sharedRules(), + sharedSwarmRouting(), + sharedMemoryAndLearning(), + sharedAgentTypes(), + sharedBuildAndTest(), + sharedCliQuickRef(), + ]; +} + +/** Claude Code's import line. Must stand on its own line, outside a code block. */ +export const AGENTS_MD_IMPORT = '@AGENTS.md'; + +/** True when the text already pulls AGENTS.md in through Claude Code's import syntax. */ +export function importsAgentsMd(text: string): boolean { + return text.split(/\r?\n/).some((line) => line.trim() === AGENTS_MD_IMPORT); +} diff --git a/v3/@claude-flow/cli/src/init/types.ts b/v3/@claude-flow/cli/src/init/types.ts index 058fcd7582..fadd3ef49b 100644 --- a/v3/@claude-flow/cli/src/init/types.ts +++ b/v3/@claude-flow/cli/src/init/types.ts @@ -364,6 +364,13 @@ export interface InitOptions { * (--drop-risky-settings). */ riskySettings?: 'stop' | 'keep' | 'drop'; + /** + * #2638 — where the shared project instructions live. `claude-md` (default, + * single-host) writes the full CLAUDE.md. `agents-md` (set by `init --dual`) + * writes CLAUDE.md as `@AGENTS.md` plus Claude-only sections; AGENTS.md, + * written by the Codex pass, carries the shared sections. + */ + instructionsSource?: 'claude-md' | 'agents-md'; } /** @@ -638,4 +645,10 @@ export interface InitResult { riskySettings?: string[]; /** ADR-509 §2.3 — init stopped before writing anything because of riskySettings. */ stoppedOnRiskySettings?: boolean; + /** + * #2638 — set when this run wrote CLAUDE.md in its `@AGENTS.md` import form. + * `fullForm` is the single-host CLAUDE.md to restore if AGENTS.md turns out + * not to carry the shared sections (see finalizeDualInstructions). + */ + dualInstructions?: { importForm: string; fullForm: string }; } diff --git a/v3/@claude-flow/codex/src/generators/agents-md.ts b/v3/@claude-flow/codex/src/generators/agents-md.ts index 6e39cfd70f..9dadbebb91 100644 --- a/v3/@claude-flow/codex/src/generators/agents-md.ts +++ b/v3/@claude-flow/codex/src/generators/agents-md.ts @@ -8,7 +8,7 @@ import type { AgentsMdOptions, AgentsMdTemplate } from '../types.js'; import { BUILT_IN_SKILLS } from '../templates/index.js'; -function concurrentRufloWorkflow(): string { +export function concurrentRufloWorkflow(): string { return `## Ruflo + Codex Automated Workflow Ruflo is the coordination ledger and policy decision point; Codex workers execute code, tests, and commands. A Ruflo coordination call records work but never replaces implementation. diff --git a/v3/@claude-flow/codex/src/generators/dual-instructions.ts b/v3/@claude-flow/codex/src/generators/dual-instructions.ts new file mode 100644 index 0000000000..08dbd221df --- /dev/null +++ b/v3/@claude-flow/codex/src/generators/dual-instructions.ts @@ -0,0 +1,118 @@ +/** + * @claude-flow/codex - dual-host instruction files (#2638) + * + * In a project set up for both Claude Code and Codex, AGENTS.md is the single + * source: the shared sections (shared-instructions.ts) plus the Codex-only + * ones. Claude Code reads it through the `@AGENTS.md` import in CLAUDE.md, so + * CLAUDE.md carries only Claude-specific notes and repeats nothing. + * + * Single-host AGENTS.md (generateAgentsMd) is untouched by this module. + */ + +import type { AgentsMdOptions } from '../types.js'; +import { BUILT_IN_SKILLS } from '../templates/index.js'; +import { concurrentRufloWorkflow } from './agents-md.js'; +import { AGENTS_MD_IMPORT, generateSharedInstructions } from './shared-instructions.js'; + +const DEFAULT_SKILLS = ['swarm-orchestration', 'memory-management', 'sparc-methodology', 'security-audit']; + +function codexOnlySections(options: AgentsMdOptions): string[] { + const { + description = 'A Claude Flow powered project', + techStack = 'TypeScript, Node.js', + buildCommand = 'npm run build', + testCommand = 'npm test', + devCommand = 'npm run dev', + skills = DEFAULT_SKILLS, + } = options; + + const skillsTable = skills + .map((skill) => { + const info = BUILT_IN_SKILLS[skill as keyof typeof BUILT_IN_SKILLS]; + return info ? `| \`$${skill}\` | ${info.description} |` : `| \`$${skill}\` | Custom skill |`; + }) + .join('\n'); + + return [ + `## Project Overview + +${description} + +**Tech Stack**: ${techStack} +**Architecture**: Domain-Driven Design with bounded contexts`, + `## Quick Start + +\`\`\`bash +npm install +${buildCommand} +${testCommand} +${devCommand} +\`\`\``, + `## Codex Execution Model + +- **claude-flow** = LEDGER (coordinates: memory, routing, swarm state) +- **Codex** = EXECUTOR (writes code, runs tests, creates files) + +**Critical rule:** DON'T STOP after calling claude-flow commands. Coordination commands return instantly — continue immediately with the next implementation step.`, + concurrentRufloWorkflow().trimEnd(), + `## Codex Skills + +Use \`$skill-name\` syntax to invoke (Claude Code uses \`/skill-name\` for the same skills): + +| Skill | Use Case | +|-------|----------| +${skillsTable}`, + `## Commit Messages + +\`\`\` +(): + +[optional body] +\`\`\` + +Types: \`feat\`, \`fix\`, \`docs\`, \`style\`, \`refactor\`, \`perf\`, \`test\`, \`chore\` + +Do not add a \`Co-Authored-By\` trailer unless the repository explicitly +configures and authorizes that attribution.`, + `## Path Security + +- Validate all file paths +- Prevent directory traversal (../) +- Use absolute paths internally`, + `## Links + +- Documentation: https://github.com/ruvnet/ruflo +- Issues: https://github.com/ruvnet/ruflo/issues`, + ]; +} + +/** AGENTS.md for a dual project: shared sections once, then Codex-only sections. */ +export function generateDualAgentsMd(options: AgentsMdOptions): string { + const header = `# ${options.projectName} + +> Shared instructions for Claude Code and OpenAI Codex. Codex reads this file +> directly; Claude Code reads it through the \`${AGENTS_MD_IMPORT}\` import in CLAUDE.md. +> Shared sections come first; the Codex-only sections follow.`; + return `${[header, ...generateSharedInstructions(), ...codexOnlySections(options)].join('\n\n')}\n`; +} + +/** + * CLAUDE.md for a dual project created by the Codex initializer: the import + * plus Claude Code notes only. (`ruflo init --dual` writes a richer Claude + * overlay itself; this initializer then leaves that file alone.) + */ +export function generateDualClaudeMdStub(projectName: string, skills: string[]): string { + return `# ${projectName} + +${AGENTS_MD_IMPORT} + +> Project instructions live in \`AGENTS.md\`, imported above; OpenAI Codex reads the same +> file. Edit shared rules there. This file holds only Claude Code notes. + +## Claude Code + +- Skills in \`.agents/skills/\` are invoked as \`/skill-name\` here and \`$skill-name\` in Codex +${skills.map((s) => ` - \`/${s}\``).join('\n')} +- Local overrides: \`CLAUDE.local.md\` (gitignored) +`; +} diff --git a/v3/@claude-flow/codex/src/generators/index.ts b/v3/@claude-flow/codex/src/generators/index.ts index 3baa602312..fbc33ecf87 100644 --- a/v3/@claude-flow/codex/src/generators/index.ts +++ b/v3/@claude-flow/codex/src/generators/index.ts @@ -7,3 +7,5 @@ export { generateAgentsMd } from './agents-md.js'; export { generateSkillMd } from './skill-md.js'; export { generateConfigToml } from './config-toml.js'; +export { generateDualAgentsMd, generateDualClaudeMdStub } from './dual-instructions.js'; +export { generateSharedInstructions, importsAgentsMd, AGENTS_MD_IMPORT } from './shared-instructions.js'; diff --git a/v3/@claude-flow/codex/src/generators/shared-instructions.ts b/v3/@claude-flow/codex/src/generators/shared-instructions.ts new file mode 100644 index 0000000000..30ef53b08a --- /dev/null +++ b/v3/@claude-flow/codex/src/generators/shared-instructions.ts @@ -0,0 +1,165 @@ +/** + * Shared Ruflo instruction sections (#2638). + * + * The host-neutral half of the project instructions: the text both Claude + * Code and Codex should read. In a dual project AGENTS.md carries these + * sections once, and CLAUDE.md pulls them in with Claude Code's `@AGENTS.md` + * import, adding only Claude-specific guidance. + * + * Canonical copy: v3/@claude-flow/codex/src/generators/shared-instructions.ts + * Mirror: v3/@claude-flow/cli/src/init/shared-instructions.ts + * + * The two files must stay byte-identical (a CLI test compares them). The CLI + * keeps a mirror instead of importing it because it pins a published + * @claude-flow/codex release, which cannot see unreleased exports; once the + * CLI pins a codex release that ships this module, the mirror can go. + * + * Pure: no imports, no I/O. + */ + +/** Rules both hosts follow. The Claude-only commit-trailer rule is kept by the CLI. */ +export const SHARED_RULE_LINES: readonly string[] = [ + '- Do what has been asked; nothing more, nothing less', + '- NEVER create files unless absolutely necessary — prefer editing existing files', + '- NEVER create documentation files unless explicitly requested', + '- NEVER save working files or tests to root — use `/src`, `/tests`, `/docs`, `/config`, `/scripts`', + '- ALWAYS read a file before editing it', + '- NEVER commit secrets, credentials, or .env files', + '- Keep files under 500 lines', + '- Validate input at system boundaries', +]; + +/** Position of the Claude-only commit-trailer rule inside the single-host Rules list. */ +export const CLAUDE_RULE_INSERT_AT = 6; + +export function sharedRules(): string { + return `## Rules\n\n${SHARED_RULE_LINES.join('\n')}`; +} + +/** Swarm body shared by both hosts: init command, routing table, when to swarm. */ +export const SWARM_ROUTING_BODY = `\`\`\`bash +npx @claude-flow/cli@latest swarm init --topology hierarchical --max-agents 8 --strategy specialized +\`\`\` + +### Agent Routing + +| Task | Agents | Topology | +|------|--------|----------| +| Bug Fix | researcher, coder, tester | hierarchical | +| Feature | architect, coder, tester, reviewer | hierarchical | +| Refactor | architect, coder, reviewer | hierarchical | +| Performance | perf-engineer, coder | hierarchical | +| Security | security-architect, auditor | hierarchical | + +### When to Swarm +- **YES**: 3+ files, new features, cross-module refactoring, API changes, security, performance +- **NO**: single file edits, 1-2 line fixes, docs updates, config changes, questions`; + +export function sharedSwarmRouting(): string { + return `## Swarm & Routing\n\n${SWARM_ROUTING_BODY}`; +} + +export function sharedMemoryAndLearning(): string { + return `## Memory & Learning + +### Before Any Task +\`\`\`bash +npx @claude-flow/cli@latest memory search --query "[task keywords]" --namespace patterns +npx @claude-flow/cli@latest hooks route --task "[task description]" +\`\`\` + +### After Success +\`\`\`bash +npx @claude-flow/cli@latest memory store --namespace patterns --key "[name]" --value "[what worked]" +npx @claude-flow/cli@latest hooks post-task --task-id "[id]" --success true --store-results true +\`\`\` + +### MCP Tools (use \`ToolSearch("keyword")\` to discover) + +| Category | Key Tools | +|----------|-----------| +| **Memory** | \`memory_store\`, \`memory_search\`, \`memory_search_unified\` | +| **Bridge** | \`memory_import_claude\`, \`memory_bridge_status\` | +| **Swarm** | \`swarm_init\`, \`swarm_status\`, \`swarm_health\` | +| **Agents** | \`agent_spawn\`, \`agent_list\`, \`agent_status\` | +| **Hooks** | \`hooks_route\`, \`hooks_post-task\`, \`hooks_worker-dispatch\` | +| **Security** | \`aidefence_scan\`, \`aidefence_is_safe\`, \`aidefence_has_pii\` | +| **Hive-Mind** | \`hive-mind_init\`, \`hive-mind_consensus\`, \`hive-mind_spawn\` | + +### Background Workers + +| Worker | When | +|--------|------| +| \`audit\` | After security changes | +| \`optimize\` | After performance work | +| \`testgaps\` | After adding features | +| \`map\` | Every 5+ file changes | +| \`document\` | After API changes | + +\`\`\`bash +npx @claude-flow/cli@latest hooks worker dispatch --trigger audit +\`\`\``; +} + +export function sharedAgentTypes(): string { + return `## Agents + +**Core**: \`coder\`, \`reviewer\`, \`tester\`, \`planner\`, \`researcher\` +**Architecture**: \`system-architect\`, \`backend-dev\`, \`mobile-dev\` +**Security**: \`security-architect\`, \`security-auditor\` +**Performance**: \`performance-engineer\`, \`perf-analyzer\` +**Coordination**: \`hierarchical-coordinator\`, \`mesh-coordinator\`, \`adaptive-coordinator\` +**GitHub**: \`pr-manager\`, \`code-review-swarm\`, \`issue-tracker\`, \`release-manager\` + +Any string works as a custom agent type.`; +} + +export function sharedBuildAndTest(): string { + return `## Build & Test + +- ALWAYS run tests after code changes +- ALWAYS verify build succeeds before committing + +\`\`\`bash +npm run build && npm test +\`\`\``; +} + +export function sharedCliQuickRef(): string { + return `## CLI Quick Reference + +\`\`\`bash +npx @claude-flow/cli@latest init --wizard # Setup +npx @claude-flow/cli@latest swarm init --v3-mode # Start swarm +npx @claude-flow/cli@latest memory search --query "" # Vector search +npx @claude-flow/cli@latest hooks route --task "" # Route to agent +npx @claude-flow/cli@latest doctor --fix # Diagnostics +npx @claude-flow/cli@latest security scan # Security scan +npx @claude-flow/cli@latest performance benchmark # Benchmarks +\`\`\` + +26 commands, 140+ subcommands. Use \`--help\` on any command for details.`; +} + +/** + * Every shared section, in order. AGENTS.md (dual mode) writes all of them; + * a CLAUDE.md that imports AGENTS.md must not repeat any of them. + */ +export function generateSharedInstructions(): string[] { + return [ + sharedRules(), + sharedSwarmRouting(), + sharedMemoryAndLearning(), + sharedAgentTypes(), + sharedBuildAndTest(), + sharedCliQuickRef(), + ]; +} + +/** Claude Code's import line. Must stand on its own line, outside a code block. */ +export const AGENTS_MD_IMPORT = '@AGENTS.md'; + +/** True when the text already pulls AGENTS.md in through Claude Code's import syntax. */ +export function importsAgentsMd(text: string): boolean { + return text.split(/\r?\n/).some((line) => line.trim() === AGENTS_MD_IMPORT); +} diff --git a/v3/@claude-flow/codex/src/initializer.ts b/v3/@claude-flow/codex/src/initializer.ts index 21f9adb850..af07e164a4 100644 --- a/v3/@claude-flow/codex/src/initializer.ts +++ b/v3/@claude-flow/codex/src/initializer.ts @@ -15,6 +15,8 @@ import type { BuiltInSkill, } from './types.js'; import { generateAgentsMd } from './generators/agents-md.js'; +import { generateDualAgentsMd, generateDualClaudeMdStub } from './generators/dual-instructions.js'; +import { importsAgentsMd } from './generators/shared-instructions.js'; import { BUILT_IN_SKILL_NAMES, generateSkillMd, @@ -570,6 +572,11 @@ export class CodexInitializer { private async generateAgentsMd(): Promise { const projectName = path.basename(this.projectPath); + // #2638: a dual project keeps the shared sections once, here. + if (this.dual) { + return generateDualAgentsMd({ projectName, skills: this.skills }); + } + return generateAgentsMd({ projectName, template: this.template, @@ -781,108 +788,30 @@ Skills are invoked using \`$skill-name\` syntax. Each skill has: const files: string[] = []; const warnings: string[] = []; - // Check if CLAUDE.md already exists + // #2638: AGENTS.md is the single source. CLAUDE.md is Claude Code's + // `@AGENTS.md` import plus Claude-only notes — never a second copy. const claudeMdPath = path.join(this.projectPath, 'CLAUDE.md'); const claudeMdExists = await fs.pathExists(claudeMdPath); + const existing = claudeMdExists ? await fs.readFile(claudeMdPath, 'utf-8') : ''; - if (claudeMdExists && !this.force) { - warnings.push('CLAUDE.md already exists - not overwriting. Use --force to replace.'); + // Already single-source (e.g. written by `ruflo init --dual`): leave it, even under --force. + if (claudeMdExists && importsAgentsMd(existing)) { return { files, warnings }; } - const projectName = path.basename(this.projectPath); + if (claudeMdExists && !this.force) { + warnings.push( + 'CLAUDE.md already exists - not overwriting. To share instructions with Claude Code, move your custom ' + + 'sections into AGENTS.md and add a line `@AGENTS.md` to CLAUDE.md, or use --force to replace it.', + ); + return { files, warnings }; + } - // Generate a CLAUDE.md that references AGENTS.md - const claudeMd = `# ${projectName} - -> This project supports both Claude Code and OpenAI Codex. - -## Platform Compatibility - -| Platform | Config File | Skill Syntax | -|----------|-------------|--------------| -| Claude Code | CLAUDE.md | /skill-name | -| OpenAI Codex | AGENTS.md | $skill-name | - -## Instructions - -**Primary instructions are in \`AGENTS.md\`** (Agentic AI Foundation standard). -Read and follow that file before starting work; it contains the live -\`guidance_brain\` routing workflow, concurrency ownership rules, and authority -boundaries. - -This file provides compatibility for Claude Code users. - -## Quick Start - -\`\`\`bash -# Install dependencies -npm install - -# Build the project -npm run build - -# Run tests -npm test -\`\`\` - -## Available Skills - -Both platforms share the same skills in \`.agents/skills/\`: - -${this.skills.map(s => `- \`$${s}\` (Codex) / \`/${s}\` (Claude Code)`).join('\n')} - -## Configuration - -### Codex Configuration -- Main: \`.agents/config.toml\` -- Local: \`.codex/config.toml\` (gitignored) - -### Claude Code Configuration -- This file: \`CLAUDE.md\` -- Local: \`CLAUDE.local.md\` (gitignored) - -## MCP Integration - -\`\`\`bash -# Start Ruflo's MCP server over stdio (dedicated entry point — the -# management \`ruflo mcp start\` CLI does NOT answer JSON-RPC on stdio). -npx -y ruflo@latest mcp start -\`\`\` - -## Swarm Orchestration - -This project uses hierarchical swarm coordination: - -| Setting | Value | -|---------|-------| -| Topology | hierarchical | -| Max Agents | 8 | -| Strategy | specialized | - -## Code Standards - -- Files under 500 lines -- No hardcoded secrets -- Input validation at boundaries -- Typed interfaces for APIs - -## Security - -- NEVER commit .env files or secrets -- Always validate user input -- Use parameterized queries for SQL - -## Full Documentation - -For complete instructions, see \`AGENTS.md\`. - ---- - -*Generated by @claude-flow/codex - Dual platform mode* -`; - - await fs.writeFile(claudeMdPath, claudeMd, 'utf-8'); + await fs.writeFile( + claudeMdPath, + generateDualClaudeMdStub(path.basename(this.projectPath), this.skills), + 'utf-8', + ); files.push('CLAUDE.md'); // Generate CLAUDE.local.md template diff --git a/v3/@claude-flow/codex/tests/__snapshots__/single-host-agents-md-snapshot-2638.test.ts.snap b/v3/@claude-flow/codex/tests/__snapshots__/single-host-agents-md-snapshot-2638.test.ts.snap new file mode 100644 index 0000000000..03c75a8fa1 --- /dev/null +++ b/v3/@claude-flow/codex/tests/__snapshots__/single-host-agents-md-snapshot-2638.test.ts.snap @@ -0,0 +1,1718 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`single-host AGENTS.md is unchanged (#2638) > CodexInitializer without --dual > writes the same AGENTS.md and no CLAUDE.md (default) 1`] = ` +"# + +> Multi-agent orchestration framework for agentic coding + +## Project Overview + +A Claude Flow powered project + +**Tech Stack**: TypeScript, Node.js +**Architecture**: Domain-Driven Design with bounded contexts + +## Quick Start + +### Installation +\`\`\`bash +npm install +\`\`\` + +### Build +\`\`\`bash +npm run build +\`\`\` + +### Test +\`\`\`bash +npm test +\`\`\` + +### Development +\`\`\`bash +npm run dev +\`\`\` + +## Agent Coordination + +### Swarm Configuration + +This project uses hierarchical swarm coordination for complex tasks: + +| Setting | Value | Purpose | +|---------|-------|---------| +| Topology | \`hierarchical\` | Queen-led coordination (anti-drift) | +| Max Agents | 8 | Optimal team size | +| Strategy | \`specialized\` | Clear role boundaries | +| Consensus | \`raft\` | Leader-based consistency | + +### When to Use Swarms + +**Invoke swarm for:** +- Multi-file changes (3+ files) +- New feature implementation +- Cross-module refactoring +- API changes with tests +- Security-related changes +- Performance optimization + +**Skip swarm for:** +- Single file edits +- Simple bug fixes (1-2 lines) +- Documentation updates +- Configuration changes + +### Available Skills + +Use \`$skill-name\` syntax to invoke: + +| Skill | Use Case | +|-------|----------| +| \`$swarm-orchestration\` | Multi-agent task coordination | +| \`$memory-management\` | Pattern storage and retrieval | +| \`$sparc-methodology\` | Structured development workflow | +| \`$security-audit\` | Security scanning and CVE detection | + +### Agent Types + +| Type | Role | Use Case | +|------|------|----------| +| \`researcher\` | Requirements analysis | Understanding scope | +| \`architect\` | System design | Planning structure | +| \`coder\` | Implementation | Writing code | +| \`tester\` | Test creation | Quality assurance | +| \`reviewer\` | Code review | Security and quality | + +## Execution Model + +- **claude-flow** = LEDGER (coordinates: memory, routing, swarm state) +- **Codex** = EXECUTOR (writes code, runs tests, creates files) + +**Critical rule:** DON'T STOP after calling claude-flow commands. Coordination commands return instantly — continue immediately with the next implementation step. + +## Ruflo + Codex Automated Workflow + +Ruflo is the coordination ledger and policy decision point; Codex workers execute code, tests, and commands. A Ruflo coordination call records work but never replaces implementation. + +Use \`guidance_brain({ mode: "recommend", task: "..." })\` when the task can +benefit from Ruflo-specific capabilities. Its live registry is authoritative +for tool presence; registration alone does not prove configuration, +reachability, health, or authorization. If it is not registered, use compatible +\`guidance_recommend\`, CLI discovery, and repository instructions. + +1. **Recall** — search AgentDB memory and relevant ADRs for patterns and constraints. +2. **Inspect** — read source, runtime, dependency, policy, and health state. +3. **Route** — choose the smallest capable topology, agents, skills, and tools. +4. **Plan** — define acceptance criteria, safety envelope, ownership, and validation. +5. **Execute** — Codex workers implement in isolated scopes; Ruflo records coordination. +6. **Test** — run focused tests, regression tests, and failure-path checks. +7. **Validate** — check types, security, policy, compatibility, and artifact integrity. +8. **Benchmark** — compare a source-bound candidate with a source-bound baseline. +9. **Optimize** — improve measured bottlenecks without weakening the safety envelope. +10. **Receipt** — bind claims, evidence, and decisions to exact source/build inputs. +11. **Handoff** — reconcile concurrent work and disclose unresolved limitations. +12. **Publish** — only an independently authorized release gate may publish immutable artifacts. + +### Concurrency and authority invariants + +- Never allow two writers in one worktree. +- Read-only research agents may share a checkout; writing agents may not. +- A child may drop capabilities but can never add tools, servers, namespaces, network access, spend, concurrency, or delegation depth. +- Cancel dependent and not-yet-started sibling work when policy denies an action or a required dependency fails. +- MetaHarness may benchmark candidates concurrently, but it cannot promote, serve, or expand its own SafetyEnvelope. +- Only the integration agent changes shared manifests or lockfiles. +- Do not auto-commit, push, merge, release, or delete worktrees unless the user authorized that operation. +- Every consequential action must produce a policy decision receipt; production, destructive, spend, and promotion actions may require human approval. + +### Repository harness adapter + +When tracked repository instructions define a local collaboration harness: + +1. Assign the isolated worktree before starting a writing session. +2. Start or register the session, inspect current claims, and acquire only the + exact paths, resources, and development ports needed for the task. +3. Renew leases during long work, check acknowledged inbox messages at integration + boundaries, and release claims when handing off or ending. +4. Record focused and integration evidence against the exact source state, + then let the designated integration owner decide release. + +A repository lease coordinates ownership; it does not grant authorization. +In-memory reference adapters demonstrate semantics but are not distributed, +restart-durable release authorities. +The worker still needs the current ADR-324/325 action capability and fencing +epoch for every protected side effect. Heartbeat and lease expiry establish +liveness; a PID is diagnostic only. HEAD alone is not an exact source-state +identity when tracked or untracked changes exist, so a release receipt must +bind a clean commit or an immutable snapshot including those changes. + + +## MCP Integration + +Use MCP tools for coordination, then keep coding: + +| Tool | Purpose | Example | +|------|---------|---------| +| \`swarm_init\` | Start coordination | \`swarm_init({topology: "hierarchical"})\` | +| \`memory_store\` | Save patterns | \`memory_store({key: "auth", value: "JWT"})\` | +| \`memory_search\` | Find patterns | \`memory_search({query: "auth patterns"})\` | +| \`task_orchestrate\` | Assign work | \`task_orchestrate({task: "implement"})\` | + +## Code Standards + +### File Organization +- **NEVER** save to root folder +- \`/src\` - Source code files +- \`/tests\` - Test files +- \`/docs\` - Documentation +- \`/config\` - Configuration files + +### Quality Rules +- Files under 500 lines +- No hardcoded secrets +- Input validation at boundaries +- Typed interfaces for public APIs +- TDD London School (mock-first) preferred + +### Commit Messages +\`\`\` +(): + +[optional body] +\`\`\` + +Types: \`feat\`, \`fix\`, \`docs\`, \`style\`, \`refactor\`, \`perf\`, \`test\`, \`chore\` + +Do not add a \`Co-Authored-By\` trailer unless the repository explicitly +configures and authorizes that attribution. + +## Security + +### Critical Rules +- NEVER commit secrets, credentials, or .env files +- NEVER hardcode API keys +- Always validate user input +- Use parameterized queries for SQL +- Sanitize output to prevent XSS + +### Path Security +- Validate all file paths +- Prevent directory traversal (../) +- Use absolute paths internally + +## Memory System + +### Storing Patterns +\`\`\`bash +npx @claude-flow/cli memory store \\ + --key "pattern-name" \\ + --value "pattern description" \\ + --namespace patterns +\`\`\` + +### Searching Memory +\`\`\`bash +npx @claude-flow/cli memory search \\ + --query "search terms" \\ + --namespace patterns +\`\`\` + +## Quick Commands + +\`\`\`bash +npx @claude-flow/cli memory search --query "relevant patterns" +npx @claude-flow/cli hooks route --task "current task description" +npx @claude-flow/cli swarm init --topology hierarchical +npx @claude-flow/cli hooks pre-task --description "task summary" +\`\`\` + +## Links + +- Documentation: https://github.com/ruvnet/ruflo +- Issues: https://github.com/ruvnet/ruflo/issues +" +`; + +exports[`single-host AGENTS.md is unchanged (#2638) > CodexInitializer without --dual > writes the same AGENTS.md and no CLAUDE.md (minimal) 1`] = ` +"# + +> A Claude Flow powered project + +## Quick Start + +### Setup +\`\`\`bash +npm install && npm run build +\`\`\` + +### Test +\`\`\`bash +npm test +\`\`\` + +## Agent Behavior + +### Code Standards +- Keep files under 500 lines +- No hardcoded secrets or credentials +- Validate input at system boundaries +- Use typed interfaces for public APIs + +### File Organization +- \`/src\` - Source code files +- \`/tests\` - Test files +- \`/docs\` - Documentation +- \`/config\` - Configuration files + +## Skills + +| Skill | Purpose | +|-------|---------| +| \`$swarm-orchestration\` | Multi-agent coordination for complex tasks | +| \`$memory-management\` | Pattern storage and semantic search | + +## Security Rules + +- NEVER commit .env files or secrets +- Always validate user inputs +- Prevent directory traversal attacks +- Use parameterized queries for databases +- Sanitize output to prevent XSS + +## Ruflo + Codex Automated Workflow + +Ruflo is the coordination ledger and policy decision point; Codex workers execute code, tests, and commands. A Ruflo coordination call records work but never replaces implementation. + +Use \`guidance_brain({ mode: "recommend", task: "..." })\` when the task can +benefit from Ruflo-specific capabilities. Its live registry is authoritative +for tool presence; registration alone does not prove configuration, +reachability, health, or authorization. If it is not registered, use compatible +\`guidance_recommend\`, CLI discovery, and repository instructions. + +1. **Recall** — search AgentDB memory and relevant ADRs for patterns and constraints. +2. **Inspect** — read source, runtime, dependency, policy, and health state. +3. **Route** — choose the smallest capable topology, agents, skills, and tools. +4. **Plan** — define acceptance criteria, safety envelope, ownership, and validation. +5. **Execute** — Codex workers implement in isolated scopes; Ruflo records coordination. +6. **Test** — run focused tests, regression tests, and failure-path checks. +7. **Validate** — check types, security, policy, compatibility, and artifact integrity. +8. **Benchmark** — compare a source-bound candidate with a source-bound baseline. +9. **Optimize** — improve measured bottlenecks without weakening the safety envelope. +10. **Receipt** — bind claims, evidence, and decisions to exact source/build inputs. +11. **Handoff** — reconcile concurrent work and disclose unresolved limitations. +12. **Publish** — only an independently authorized release gate may publish immutable artifacts. + +### Concurrency and authority invariants + +- Never allow two writers in one worktree. +- Read-only research agents may share a checkout; writing agents may not. +- A child may drop capabilities but can never add tools, servers, namespaces, network access, spend, concurrency, or delegation depth. +- Cancel dependent and not-yet-started sibling work when policy denies an action or a required dependency fails. +- MetaHarness may benchmark candidates concurrently, but it cannot promote, serve, or expand its own SafetyEnvelope. +- Only the integration agent changes shared manifests or lockfiles. +- Do not auto-commit, push, merge, release, or delete worktrees unless the user authorized that operation. +- Every consequential action must produce a policy decision receipt; production, destructive, spend, and promotion actions may require human approval. + +### Repository harness adapter + +When tracked repository instructions define a local collaboration harness: + +1. Assign the isolated worktree before starting a writing session. +2. Start or register the session, inspect current claims, and acquire only the + exact paths, resources, and development ports needed for the task. +3. Renew leases during long work, check acknowledged inbox messages at integration + boundaries, and release claims when handing off or ending. +4. Record focused and integration evidence against the exact source state, + then let the designated integration owner decide release. + +A repository lease coordinates ownership; it does not grant authorization. +In-memory reference adapters demonstrate semantics but are not distributed, +restart-durable release authorities. +The worker still needs the current ADR-324/325 action capability and fencing +epoch for every protected side effect. Heartbeat and lease expiry establish +liveness; a PID is diagnostic only. HEAD alone is not an exact source-state +identity when tracked or untracked changes exist, so a release receipt must +bind a clean commit or an immutable snapshot including those changes. + + +## Links + +- Documentation: https://github.com/ruvnet/ruflo +" +`; + +exports[`single-host AGENTS.md is unchanged (#2638) > generateAgentsMd(default) 1`] = ` +"# snapshot-project + +> Multi-agent orchestration framework for agentic coding + +## Project Overview + +A Claude Flow powered project + +**Tech Stack**: TypeScript, Node.js +**Architecture**: Domain-Driven Design with bounded contexts + +## Quick Start + +### Installation +\`\`\`bash +npm install +\`\`\` + +### Build +\`\`\`bash +npm run build +\`\`\` + +### Test +\`\`\`bash +npm test +\`\`\` + +### Development +\`\`\`bash +npm run dev +\`\`\` + +## Agent Coordination + +### Swarm Configuration + +This project uses hierarchical swarm coordination for complex tasks: + +| Setting | Value | Purpose | +|---------|-------|---------| +| Topology | \`hierarchical\` | Queen-led coordination (anti-drift) | +| Max Agents | 8 | Optimal team size | +| Strategy | \`specialized\` | Clear role boundaries | +| Consensus | \`raft\` | Leader-based consistency | + +### When to Use Swarms + +**Invoke swarm for:** +- Multi-file changes (3+ files) +- New feature implementation +- Cross-module refactoring +- API changes with tests +- Security-related changes +- Performance optimization + +**Skip swarm for:** +- Single file edits +- Simple bug fixes (1-2 lines) +- Documentation updates +- Configuration changes + +### Available Skills + +Use \`$skill-name\` syntax to invoke: + +| Skill | Use Case | +|-------|----------| +| \`$swarm-orchestration\` | Multi-agent task coordination | +| \`$memory-management\` | Pattern storage and retrieval | +| \`$sparc-methodology\` | Structured development workflow | +| \`$security-audit\` | Security scanning and CVE detection | + +### Agent Types + +| Type | Role | Use Case | +|------|------|----------| +| \`researcher\` | Requirements analysis | Understanding scope | +| \`architect\` | System design | Planning structure | +| \`coder\` | Implementation | Writing code | +| \`tester\` | Test creation | Quality assurance | +| \`reviewer\` | Code review | Security and quality | + +## Execution Model + +- **claude-flow** = LEDGER (coordinates: memory, routing, swarm state) +- **Codex** = EXECUTOR (writes code, runs tests, creates files) + +**Critical rule:** DON'T STOP after calling claude-flow commands. Coordination commands return instantly — continue immediately with the next implementation step. + +## Ruflo + Codex Automated Workflow + +Ruflo is the coordination ledger and policy decision point; Codex workers execute code, tests, and commands. A Ruflo coordination call records work but never replaces implementation. + +Use \`guidance_brain({ mode: "recommend", task: "..." })\` when the task can +benefit from Ruflo-specific capabilities. Its live registry is authoritative +for tool presence; registration alone does not prove configuration, +reachability, health, or authorization. If it is not registered, use compatible +\`guidance_recommend\`, CLI discovery, and repository instructions. + +1. **Recall** — search AgentDB memory and relevant ADRs for patterns and constraints. +2. **Inspect** — read source, runtime, dependency, policy, and health state. +3. **Route** — choose the smallest capable topology, agents, skills, and tools. +4. **Plan** — define acceptance criteria, safety envelope, ownership, and validation. +5. **Execute** — Codex workers implement in isolated scopes; Ruflo records coordination. +6. **Test** — run focused tests, regression tests, and failure-path checks. +7. **Validate** — check types, security, policy, compatibility, and artifact integrity. +8. **Benchmark** — compare a source-bound candidate with a source-bound baseline. +9. **Optimize** — improve measured bottlenecks without weakening the safety envelope. +10. **Receipt** — bind claims, evidence, and decisions to exact source/build inputs. +11. **Handoff** — reconcile concurrent work and disclose unresolved limitations. +12. **Publish** — only an independently authorized release gate may publish immutable artifacts. + +### Concurrency and authority invariants + +- Never allow two writers in one worktree. +- Read-only research agents may share a checkout; writing agents may not. +- A child may drop capabilities but can never add tools, servers, namespaces, network access, spend, concurrency, or delegation depth. +- Cancel dependent and not-yet-started sibling work when policy denies an action or a required dependency fails. +- MetaHarness may benchmark candidates concurrently, but it cannot promote, serve, or expand its own SafetyEnvelope. +- Only the integration agent changes shared manifests or lockfiles. +- Do not auto-commit, push, merge, release, or delete worktrees unless the user authorized that operation. +- Every consequential action must produce a policy decision receipt; production, destructive, spend, and promotion actions may require human approval. + +### Repository harness adapter + +When tracked repository instructions define a local collaboration harness: + +1. Assign the isolated worktree before starting a writing session. +2. Start or register the session, inspect current claims, and acquire only the + exact paths, resources, and development ports needed for the task. +3. Renew leases during long work, check acknowledged inbox messages at integration + boundaries, and release claims when handing off or ending. +4. Record focused and integration evidence against the exact source state, + then let the designated integration owner decide release. + +A repository lease coordinates ownership; it does not grant authorization. +In-memory reference adapters demonstrate semantics but are not distributed, +restart-durable release authorities. +The worker still needs the current ADR-324/325 action capability and fencing +epoch for every protected side effect. Heartbeat and lease expiry establish +liveness; a PID is diagnostic only. HEAD alone is not an exact source-state +identity when tracked or untracked changes exist, so a release receipt must +bind a clean commit or an immutable snapshot including those changes. + + +## MCP Integration + +Use MCP tools for coordination, then keep coding: + +| Tool | Purpose | Example | +|------|---------|---------| +| \`swarm_init\` | Start coordination | \`swarm_init({topology: "hierarchical"})\` | +| \`memory_store\` | Save patterns | \`memory_store({key: "auth", value: "JWT"})\` | +| \`memory_search\` | Find patterns | \`memory_search({query: "auth patterns"})\` | +| \`task_orchestrate\` | Assign work | \`task_orchestrate({task: "implement"})\` | + +## Code Standards + +### File Organization +- **NEVER** save to root folder +- \`/src\` - Source code files +- \`/tests\` - Test files +- \`/docs\` - Documentation +- \`/config\` - Configuration files + +### Quality Rules +- Files under 500 lines +- No hardcoded secrets +- Input validation at boundaries +- Typed interfaces for public APIs +- TDD London School (mock-first) preferred + +### Commit Messages +\`\`\` +(): + +[optional body] +\`\`\` + +Types: \`feat\`, \`fix\`, \`docs\`, \`style\`, \`refactor\`, \`perf\`, \`test\`, \`chore\` + +Do not add a \`Co-Authored-By\` trailer unless the repository explicitly +configures and authorizes that attribution. + +## Security + +### Critical Rules +- NEVER commit secrets, credentials, or .env files +- NEVER hardcode API keys +- Always validate user input +- Use parameterized queries for SQL +- Sanitize output to prevent XSS + +### Path Security +- Validate all file paths +- Prevent directory traversal (../) +- Use absolute paths internally + +## Memory System + +### Storing Patterns +\`\`\`bash +npx @claude-flow/cli memory store \\ + --key "pattern-name" \\ + --value "pattern description" \\ + --namespace patterns +\`\`\` + +### Searching Memory +\`\`\`bash +npx @claude-flow/cli memory search \\ + --query "search terms" \\ + --namespace patterns +\`\`\` + +## Quick Commands + +\`\`\`bash +npx @claude-flow/cli memory search --query "relevant patterns" +npx @claude-flow/cli hooks route --task "current task description" +npx @claude-flow/cli swarm init --topology hierarchical +npx @claude-flow/cli hooks pre-task --description "task summary" +\`\`\` + +## Links + +- Documentation: https://github.com/ruvnet/ruflo +- Issues: https://github.com/ruvnet/ruflo/issues +" +`; + +exports[`single-host AGENTS.md is unchanged (#2638) > generateAgentsMd(enterprise) 1`] = ` +"# snapshot-project + +> Multi-agent orchestration framework for agentic coding + +## Project Overview + +A Claude Flow powered project + +**Tech Stack**: TypeScript, Node.js +**Architecture**: Domain-Driven Design with bounded contexts + +## Quick Start + +### Installation +\`\`\`bash +npm install +\`\`\` + +### Build +\`\`\`bash +npm run build +\`\`\` + +### Test +\`\`\`bash +npm test +\`\`\` + +### Development +\`\`\`bash +npm run dev +\`\`\` + +## Agent Coordination + +### Swarm Configuration + +This project uses hierarchical swarm coordination for complex tasks: + +| Setting | Value | Purpose | +|---------|-------|---------| +| Topology | \`hierarchical\` | Queen-led coordination (anti-drift) | +| Max Agents | 8 | Optimal team size | +| Strategy | \`specialized\` | Clear role boundaries | +| Consensus | \`raft\` | Leader-based consistency | + +### When to Use Swarms + +**Invoke swarm for:** +- Multi-file changes (3+ files) +- New feature implementation +- Cross-module refactoring +- API changes with tests +- Security-related changes +- Performance optimization + +**Skip swarm for:** +- Single file edits +- Simple bug fixes (1-2 lines) +- Documentation updates +- Configuration changes + +### Available Skills + +Use \`$skill-name\` syntax to invoke: + +| Skill | Use Case | +|-------|----------| +| \`$swarm-orchestration\` | Multi-agent task coordination | +| \`$memory-management\` | Pattern storage and retrieval | +| \`$sparc-methodology\` | Structured development workflow | +| \`$security-audit\` | Security scanning and CVE detection | + +### Agent Types + +| Type | Role | Use Case | +|------|------|----------| +| \`researcher\` | Requirements analysis | Understanding scope | +| \`architect\` | System design | Planning structure | +| \`coder\` | Implementation | Writing code | +| \`tester\` | Test creation | Quality assurance | +| \`reviewer\` | Code review | Security and quality | + +## Execution Model + +- **claude-flow** = LEDGER (coordinates: memory, routing, swarm state) +- **Codex** = EXECUTOR (writes code, runs tests, creates files) + +**Critical rule:** DON'T STOP after calling claude-flow commands. Coordination commands return instantly — continue immediately with the next implementation step. + +## Ruflo + Codex Automated Workflow + +Ruflo is the coordination ledger and policy decision point; Codex workers execute code, tests, and commands. A Ruflo coordination call records work but never replaces implementation. + +Use \`guidance_brain({ mode: "recommend", task: "..." })\` when the task can +benefit from Ruflo-specific capabilities. Its live registry is authoritative +for tool presence; registration alone does not prove configuration, +reachability, health, or authorization. If it is not registered, use compatible +\`guidance_recommend\`, CLI discovery, and repository instructions. + +1. **Recall** — search AgentDB memory and relevant ADRs for patterns and constraints. +2. **Inspect** — read source, runtime, dependency, policy, and health state. +3. **Route** — choose the smallest capable topology, agents, skills, and tools. +4. **Plan** — define acceptance criteria, safety envelope, ownership, and validation. +5. **Execute** — Codex workers implement in isolated scopes; Ruflo records coordination. +6. **Test** — run focused tests, regression tests, and failure-path checks. +7. **Validate** — check types, security, policy, compatibility, and artifact integrity. +8. **Benchmark** — compare a source-bound candidate with a source-bound baseline. +9. **Optimize** — improve measured bottlenecks without weakening the safety envelope. +10. **Receipt** — bind claims, evidence, and decisions to exact source/build inputs. +11. **Handoff** — reconcile concurrent work and disclose unresolved limitations. +12. **Publish** — only an independently authorized release gate may publish immutable artifacts. + +### Concurrency and authority invariants + +- Never allow two writers in one worktree. +- Read-only research agents may share a checkout; writing agents may not. +- A child may drop capabilities but can never add tools, servers, namespaces, network access, spend, concurrency, or delegation depth. +- Cancel dependent and not-yet-started sibling work when policy denies an action or a required dependency fails. +- MetaHarness may benchmark candidates concurrently, but it cannot promote, serve, or expand its own SafetyEnvelope. +- Only the integration agent changes shared manifests or lockfiles. +- Do not auto-commit, push, merge, release, or delete worktrees unless the user authorized that operation. +- Every consequential action must produce a policy decision receipt; production, destructive, spend, and promotion actions may require human approval. + +### Repository harness adapter + +When tracked repository instructions define a local collaboration harness: + +1. Assign the isolated worktree before starting a writing session. +2. Start or register the session, inspect current claims, and acquire only the + exact paths, resources, and development ports needed for the task. +3. Renew leases during long work, check acknowledged inbox messages at integration + boundaries, and release claims when handing off or ending. +4. Record focused and integration evidence against the exact source state, + then let the designated integration owner decide release. + +A repository lease coordinates ownership; it does not grant authorization. +In-memory reference adapters demonstrate semantics but are not distributed, +restart-durable release authorities. +The worker still needs the current ADR-324/325 action capability and fencing +epoch for every protected side effect. Heartbeat and lease expiry establish +liveness; a PID is diagnostic only. HEAD alone is not an exact source-state +identity when tracked or untracked changes exist, so a release receipt must +bind a clean commit or an immutable snapshot including those changes. + + +## MCP Integration + +Use MCP tools for coordination, then keep coding: + +| Tool | Purpose | Example | +|------|---------|---------| +| \`swarm_init\` | Start coordination | \`swarm_init({topology: "hierarchical"})\` | +| \`memory_store\` | Save patterns | \`memory_store({key: "auth", value: "JWT"})\` | +| \`memory_search\` | Find patterns | \`memory_search({query: "auth patterns"})\` | +| \`task_orchestrate\` | Assign work | \`task_orchestrate({task: "implement"})\` | + +## Code Standards + +### File Organization +- **NEVER** save to root folder +- \`/src\` - Source code files +- \`/tests\` - Test files +- \`/docs\` - Documentation +- \`/config\` - Configuration files + +### Quality Rules +- Files under 500 lines +- No hardcoded secrets +- Input validation at boundaries +- Typed interfaces for public APIs +- TDD London School (mock-first) preferred + +### Commit Messages +\`\`\` +(): + +[optional body] +\`\`\` + +Types: \`feat\`, \`fix\`, \`docs\`, \`style\`, \`refactor\`, \`perf\`, \`test\`, \`chore\` + +Do not add a \`Co-Authored-By\` trailer unless the repository explicitly +configures and authorizes that attribution. + +## Security + +### Critical Rules +- NEVER commit secrets, credentials, or .env files +- NEVER hardcode API keys +- Always validate user input +- Use parameterized queries for SQL +- Sanitize output to prevent XSS + +### Path Security +- Validate all file paths +- Prevent directory traversal (../) +- Use absolute paths internally + +## Memory System + +### Storing Patterns +\`\`\`bash +npx @claude-flow/cli memory store \\ + --key "pattern-name" \\ + --value "pattern description" \\ + --namespace patterns +\`\`\` + +### Searching Memory +\`\`\`bash +npx @claude-flow/cli memory search \\ + --query "search terms" \\ + --namespace patterns +\`\`\` + +## Quick Commands + +\`\`\`bash +npx @claude-flow/cli memory search --query "relevant patterns" +npx @claude-flow/cli hooks route --task "current task description" +npx @claude-flow/cli swarm init --topology hierarchical +npx @claude-flow/cli hooks pre-task --description "task summary" +\`\`\` + +## Links + +- Documentation: https://github.com/ruvnet/ruflo +- Issues: https://github.com/ruvnet/ruflo/issues + +## Performance Targets + +| Metric | Target | Notes | +|--------|--------|-------| +| HNSW Search | 150x-12,500x faster | Vector operations | +| Memory Reduction | 50-75% | Int8 quantization | +| MCP Response | <100ms | API latency | +| CLI Startup | <500ms | Cold start | +| SONA Adaptation | <0.05ms | Neural learning | + +## Testing + +### Running Tests +\`\`\`bash +# Unit tests +npm test + +# Integration tests +npm run test:integration + +# Coverage +npm run test:coverage + +# Security tests +npm run test:security +\`\`\` + +### Test Philosophy +- TDD London School (mock-first) +- Unit tests for business logic +- Integration tests for boundaries +- E2E tests for critical paths +- Security tests for sensitive operations + +### Coverage Requirements +- Minimum 80% line coverage +- 100% coverage for security-critical code +- All public APIs must have tests + +## MCP Integration + +Claude Flow exposes tools via Model Context Protocol: + +\`\`\`bash +# Start MCP server +npx ruflo mcp start + +# List available tools +npx ruflo mcp tools +\`\`\` + +### Available Tools + +| Tool | Purpose | Example | +|------|---------|---------| +| \`swarm_init\` | Initialize swarm coordination | \`swarm_init({topology: "hierarchical"})\` | +| \`agent_spawn\` | Spawn new agents | \`agent_spawn({type: "coder", name: "dev-1"})\` | +| \`memory_store\` | Store in AgentDB | \`memory_store({key: "pattern", value: "..."})\` | +| \`memory_search\` | Semantic search | \`memory_search({query: "auth patterns"})\` | +| \`task_orchestrate\` | Task coordination | \`task_orchestrate({task: "implement feature"})\` | +| \`neural_train\` | Train neural patterns | \`neural_train({iterations: 10})\` | +| \`benchmark_run\` | Performance benchmarks | \`benchmark_run({type: "all"})\` | + +## Hooks System + +Claude Flow uses hooks for lifecycle automation: + +### Core Hooks + +| Hook | Trigger | Purpose | +|------|---------|---------| +| \`pre-task\` | Before task starts | Get context, load patterns | +| \`post-task\` | After task completes | Record completion, train | +| \`pre-edit\` | Before file changes | Validate, backup | +| \`post-edit\` | After file changes | Train patterns, verify | +| \`pre-command\` | Before shell commands | Security check | +| \`post-command\` | After shell commands | Log results | + +### Session Hooks + +| Hook | Purpose | +|------|---------| +| \`session-start\` | Initialize context, load memory | +| \`session-end\` | Export metrics, consolidate memory | +| \`session-restore\` | Resume from checkpoint | +| \`notify\` | Send notifications | + +### Intelligence Hooks + +| Hook | Purpose | +|------|---------| +| \`route\` | Route task to appropriate agents | +| \`explain\` | Generate explanations | +| \`pretrain\` | Pre-train neural patterns | +| \`build-agents\` | Build specialized agents | +| \`transfer\` | Transfer learning between domains | + +### Example Usage +\`\`\`bash +# Before starting a task +npx @claude-flow/cli hooks pre-task \\ + --description "implementing authentication" + +# After completing a task +npx @claude-flow/cli hooks post-task \\ + --task-id "task-123" \\ + --success true + +# Route a task to agents +npx @claude-flow/cli hooks route \\ + --task "implement OAuth2 login flow" +\`\`\` + +## Background Workers + +12 background workers provide continuous optimization: + +| Worker | Priority | Purpose | +|--------|----------|---------| +| \`ultralearn\` | normal | Deep knowledge acquisition | +| \`optimize\` | high | Performance optimization | +| \`consolidate\` | low | Memory consolidation | +| \`predict\` | normal | Predictive preloading | +| \`audit\` | critical | Security analysis | +| \`map\` | normal | Codebase mapping | +| \`preload\` | low | Resource preloading | +| \`deepdive\` | normal | Deep code analysis | +| \`document\` | normal | Auto-documentation | +| \`refactor\` | normal | Refactoring suggestions | +| \`benchmark\` | normal | Performance benchmarking | +| \`testgaps\` | normal | Test coverage analysis | + +### Managing Workers +\`\`\`bash +# List workers +npx @claude-flow/cli hooks worker list + +# Trigger specific worker +npx @claude-flow/cli hooks worker dispatch --trigger audit + +# Check worker status +npx @claude-flow/cli hooks worker status +\`\`\` + +## Intelligence System + +The RuVector Intelligence System provides neural learning: + +### Components +- **SONA**: Self-Optimizing Neural Architecture (<0.05ms adaptation) +- **MoE**: Mixture of Experts for specialized routing +- **HNSW**: Hierarchical Navigable Small World for fast search +- **EWC++**: Elastic Weight Consolidation (prevents forgetting) +- **Flash Attention**: Optimized attention mechanism + +### 4-Step Pipeline +1. **RETRIEVE** - Fetch relevant patterns via HNSW +2. **JUDGE** - Evaluate with verdicts (success/failure) +3. **DISTILL** - Extract key learnings via LoRA +4. **CONSOLIDATE** - Prevent catastrophic forgetting via EWC++ + +## Debugging + +### Log Levels +\`\`\`bash +# Set log level +export CLAUDE_FLOW_LOG_LEVEL=debug + +# Enable verbose mode +npx @claude-flow/cli --verbose +\`\`\` + +### Health Checks +\`\`\`bash +# Run diagnostics +npx @claude-flow/cli doctor --fix + +# Check system status +npx @claude-flow/cli status +\`\`\` + +## Governance + +### Approval Workflow +All significant changes require: +1. Code review by designated reviewer +2. Security scan passing +3. Test coverage > 80% +4. Documentation update +5. Change request ticket linked + +### Change Classification + +| Class | Approval | Review Time | Examples | +|-------|----------|-------------|----------| +| Standard | Auto | <1 hour | Bug fixes, docs, config | +| Normal | 1 reviewer | <4 hours | Features, refactoring | +| Major | 2 reviewers | <24 hours | Architecture, security | +| Emergency | Skip + post-review | Immediate | Production hotfix | + +### Audit Trail +All agent actions are logged to: +- \`/logs/agent-actions.log\` - Local file log +- \`/logs/audit.json\` - Structured JSON log +- Central audit system (if configured via AUDIT_ENDPOINT) + +\`\`\`bash +# View recent agent actions +npx @claude-flow/cli logs --type agent-actions --last 1h + +# Export audit log +npx @claude-flow/cli logs export --format json --output audit.json +\`\`\` + +### Compliance + +#### SOC2 Controls +- All actions timestamped with actor ID +- Immutable audit log retention (90 days minimum) +- Access control for sensitive operations +- Automated security scanning + +#### GDPR Data Handling +- PII detection and masking in logs +- Data minimization in memory storage +- Right to erasure support in AgentDB +- Cross-border transfer controls + +#### PCI-DSS (if applicable) +- No storage of card data in agent memory +- Encrypted communication for sensitive data +- Access logging for cardholder data operations +- Quarterly security reviews + +### Role-Based Access Control (RBAC) + +| Role | Permissions | +|------|-------------| +| Developer | Read, write source code, run tests | +| Lead | Developer + approve PRs, deploy to staging | +| Admin | Lead + deploy to production, manage config | +| Security | Audit logs, security scans, CVE remediation | +| Observer | Read-only access to logs and metrics | + +\`\`\`bash +# Check current role +npx @claude-flow/cli claims list + +# Request elevated permissions +npx @claude-flow/cli claims request --permission deploy:production +\`\`\` + +## Service Level Agreements (SLAs) + +### Agent Response Times + +| Operation | Target | Max | Escalation | +|-----------|--------|-----|------------| +| Code generation | <5s | 30s | Alert on-call | +| Memory search | <100ms | 500ms | Log warning | +| Security scan | <60s | 5min | Queue retry | +| Test execution | <2min | 10min | Split test suite | + +### Availability Targets +- Agent availability: 99.9% uptime +- Memory system: 99.99% availability +- MCP server: 99.5% uptime + +## Incident Response + +### Severity Levels + +| Level | Description | Response Time | Notification | +|-------|-------------|---------------|--------------| +| P1 | Production down | <15 min | Page on-call | +| P2 | Major feature broken | <1 hour | Slack alert | +| P3 | Minor issue | <4 hours | Email | +| P4 | Cosmetic/docs | Next sprint | Ticket | + +### On Security Issue +1. **Contain** - Immediately stop affected agents + \`\`\`bash + npx @claude-flow/cli agent stop --all --force + \`\`\` +2. **Isolate** - Quarantine compromised resources +3. **Document** - Record timeline in incident log +4. **Notify** - Alert security team via configured channel +5. **Remediate** - Apply fix with expedited review +6. **Review** - Post-incident analysis within 48 hours + +### On Production Bug +1. **Assess** - Determine impact and scope +2. **Decide** - Roll back if safe, or forward-fix + \`\`\`bash + # Rollback + npx @claude-flow/cli deployment rollback --env production + + # Or forward-fix + npx @claude-flow/cli workflow run hotfix + \`\`\` +3. **Document** - Capture reproduction steps +4. **Fix** - Create hotfix on dedicated branch +5. **Validate** - Full regression test suite +6. **Deploy** - With expedited review process + +### Communication Templates + +\`\`\`markdown +# Incident Started +**Status**: Investigating +**Impact**: [Brief description] +**Started**: [Timestamp] +**Next Update**: [ETA] + +# Incident Resolved +**Status**: Resolved +**Impact**: [Summary] +**Duration**: [Time] +**Root Cause**: [Brief description] +**Prevention**: [Actions taken] +\`\`\` + +## Disaster Recovery + +### Backup Strategy +- **Memory DB**: Hourly snapshots, 7-day retention +- **Configuration**: Version controlled, immutable +- **Agent State**: Checkpoint every 10 tasks + +### Recovery Procedures +\`\`\`bash +# Restore from backup +npx @claude-flow/cli memory restore --snapshot latest + +# Restore specific checkpoint +npx @claude-flow/cli session restore --checkpoint +\`\`\` + +### Recovery Time Objectives +| Component | RTO | RPO | +|-----------|-----|-----| +| Memory DB | <1 hour | <1 hour | +| Agent State | <15 min | <10 tasks | +| Configuration | <5 min | 0 (git) | + +## Monitoring & Alerting + +### Key Metrics +- Agent task completion rate +- Average response latency +- Error rate by type +- Memory usage trends +- Security scan findings + +### Alert Thresholds +\`\`\`yaml +alerts: + - name: high_error_rate + condition: error_rate > 5% + duration: 5m + severity: critical + + - name: slow_response + condition: p99_latency > 10s + duration: 10m + severity: warning + + - name: memory_pressure + condition: memory_usage > 90% + duration: 1m + severity: critical +\`\`\` + +## Training & Onboarding + +### New Team Member Checklist +- [ ] Read this AGENTS.md document +- [ ] Complete security awareness training +- [ ] Set up local development environment +- [ ] Run \`npx @claude-flow/cli doctor\` to verify setup +- [ ] Complete first guided task with mentor +- [ ] Review incident response procedures + +### Knowledge Base +- Internal wiki: [Link to wiki] +- Architecture Decision Records: \`/docs/adr/\` +- Runbooks: \`/docs/runbooks/\` +" +`; + +exports[`single-host AGENTS.md is unchanged (#2638) > generateAgentsMd(full) 1`] = ` +"# snapshot-project + +> Multi-agent orchestration framework for agentic coding + +## Project Overview + +A Claude Flow powered project + +**Tech Stack**: TypeScript, Node.js +**Architecture**: Domain-Driven Design with bounded contexts + +## Quick Start + +### Installation +\`\`\`bash +npm install +\`\`\` + +### Build +\`\`\`bash +npm run build +\`\`\` + +### Test +\`\`\`bash +npm test +\`\`\` + +### Development +\`\`\`bash +npm run dev +\`\`\` + +## Agent Coordination + +### Swarm Configuration + +This project uses hierarchical swarm coordination for complex tasks: + +| Setting | Value | Purpose | +|---------|-------|---------| +| Topology | \`hierarchical\` | Queen-led coordination (anti-drift) | +| Max Agents | 8 | Optimal team size | +| Strategy | \`specialized\` | Clear role boundaries | +| Consensus | \`raft\` | Leader-based consistency | + +### When to Use Swarms + +**Invoke swarm for:** +- Multi-file changes (3+ files) +- New feature implementation +- Cross-module refactoring +- API changes with tests +- Security-related changes +- Performance optimization + +**Skip swarm for:** +- Single file edits +- Simple bug fixes (1-2 lines) +- Documentation updates +- Configuration changes + +### Available Skills + +Use \`$skill-name\` syntax to invoke: + +| Skill | Use Case | +|-------|----------| +| \`$swarm-orchestration\` | Multi-agent task coordination | +| \`$memory-management\` | Pattern storage and retrieval | +| \`$sparc-methodology\` | Structured development workflow | +| \`$security-audit\` | Security scanning and CVE detection | + +### Agent Types + +| Type | Role | Use Case | +|------|------|----------| +| \`researcher\` | Requirements analysis | Understanding scope | +| \`architect\` | System design | Planning structure | +| \`coder\` | Implementation | Writing code | +| \`tester\` | Test creation | Quality assurance | +| \`reviewer\` | Code review | Security and quality | + +## Execution Model + +- **claude-flow** = LEDGER (coordinates: memory, routing, swarm state) +- **Codex** = EXECUTOR (writes code, runs tests, creates files) + +**Critical rule:** DON'T STOP after calling claude-flow commands. Coordination commands return instantly — continue immediately with the next implementation step. + +## Ruflo + Codex Automated Workflow + +Ruflo is the coordination ledger and policy decision point; Codex workers execute code, tests, and commands. A Ruflo coordination call records work but never replaces implementation. + +Use \`guidance_brain({ mode: "recommend", task: "..." })\` when the task can +benefit from Ruflo-specific capabilities. Its live registry is authoritative +for tool presence; registration alone does not prove configuration, +reachability, health, or authorization. If it is not registered, use compatible +\`guidance_recommend\`, CLI discovery, and repository instructions. + +1. **Recall** — search AgentDB memory and relevant ADRs for patterns and constraints. +2. **Inspect** — read source, runtime, dependency, policy, and health state. +3. **Route** — choose the smallest capable topology, agents, skills, and tools. +4. **Plan** — define acceptance criteria, safety envelope, ownership, and validation. +5. **Execute** — Codex workers implement in isolated scopes; Ruflo records coordination. +6. **Test** — run focused tests, regression tests, and failure-path checks. +7. **Validate** — check types, security, policy, compatibility, and artifact integrity. +8. **Benchmark** — compare a source-bound candidate with a source-bound baseline. +9. **Optimize** — improve measured bottlenecks without weakening the safety envelope. +10. **Receipt** — bind claims, evidence, and decisions to exact source/build inputs. +11. **Handoff** — reconcile concurrent work and disclose unresolved limitations. +12. **Publish** — only an independently authorized release gate may publish immutable artifacts. + +### Concurrency and authority invariants + +- Never allow two writers in one worktree. +- Read-only research agents may share a checkout; writing agents may not. +- A child may drop capabilities but can never add tools, servers, namespaces, network access, spend, concurrency, or delegation depth. +- Cancel dependent and not-yet-started sibling work when policy denies an action or a required dependency fails. +- MetaHarness may benchmark candidates concurrently, but it cannot promote, serve, or expand its own SafetyEnvelope. +- Only the integration agent changes shared manifests or lockfiles. +- Do not auto-commit, push, merge, release, or delete worktrees unless the user authorized that operation. +- Every consequential action must produce a policy decision receipt; production, destructive, spend, and promotion actions may require human approval. + +### Repository harness adapter + +When tracked repository instructions define a local collaboration harness: + +1. Assign the isolated worktree before starting a writing session. +2. Start or register the session, inspect current claims, and acquire only the + exact paths, resources, and development ports needed for the task. +3. Renew leases during long work, check acknowledged inbox messages at integration + boundaries, and release claims when handing off or ending. +4. Record focused and integration evidence against the exact source state, + then let the designated integration owner decide release. + +A repository lease coordinates ownership; it does not grant authorization. +In-memory reference adapters demonstrate semantics but are not distributed, +restart-durable release authorities. +The worker still needs the current ADR-324/325 action capability and fencing +epoch for every protected side effect. Heartbeat and lease expiry establish +liveness; a PID is diagnostic only. HEAD alone is not an exact source-state +identity when tracked or untracked changes exist, so a release receipt must +bind a clean commit or an immutable snapshot including those changes. + + +## MCP Integration + +Use MCP tools for coordination, then keep coding: + +| Tool | Purpose | Example | +|------|---------|---------| +| \`swarm_init\` | Start coordination | \`swarm_init({topology: "hierarchical"})\` | +| \`memory_store\` | Save patterns | \`memory_store({key: "auth", value: "JWT"})\` | +| \`memory_search\` | Find patterns | \`memory_search({query: "auth patterns"})\` | +| \`task_orchestrate\` | Assign work | \`task_orchestrate({task: "implement"})\` | + +## Code Standards + +### File Organization +- **NEVER** save to root folder +- \`/src\` - Source code files +- \`/tests\` - Test files +- \`/docs\` - Documentation +- \`/config\` - Configuration files + +### Quality Rules +- Files under 500 lines +- No hardcoded secrets +- Input validation at boundaries +- Typed interfaces for public APIs +- TDD London School (mock-first) preferred + +### Commit Messages +\`\`\` +(): + +[optional body] +\`\`\` + +Types: \`feat\`, \`fix\`, \`docs\`, \`style\`, \`refactor\`, \`perf\`, \`test\`, \`chore\` + +Do not add a \`Co-Authored-By\` trailer unless the repository explicitly +configures and authorizes that attribution. + +## Security + +### Critical Rules +- NEVER commit secrets, credentials, or .env files +- NEVER hardcode API keys +- Always validate user input +- Use parameterized queries for SQL +- Sanitize output to prevent XSS + +### Path Security +- Validate all file paths +- Prevent directory traversal (../) +- Use absolute paths internally + +## Memory System + +### Storing Patterns +\`\`\`bash +npx @claude-flow/cli memory store \\ + --key "pattern-name" \\ + --value "pattern description" \\ + --namespace patterns +\`\`\` + +### Searching Memory +\`\`\`bash +npx @claude-flow/cli memory search \\ + --query "search terms" \\ + --namespace patterns +\`\`\` + +## Quick Commands + +\`\`\`bash +npx @claude-flow/cli memory search --query "relevant patterns" +npx @claude-flow/cli hooks route --task "current task description" +npx @claude-flow/cli swarm init --topology hierarchical +npx @claude-flow/cli hooks pre-task --description "task summary" +\`\`\` + +## Links + +- Documentation: https://github.com/ruvnet/ruflo +- Issues: https://github.com/ruvnet/ruflo/issues + +## Performance Targets + +| Metric | Target | Notes | +|--------|--------|-------| +| HNSW Search | 150x-12,500x faster | Vector operations | +| Memory Reduction | 50-75% | Int8 quantization | +| MCP Response | <100ms | API latency | +| CLI Startup | <500ms | Cold start | +| SONA Adaptation | <0.05ms | Neural learning | + +## Testing + +### Running Tests +\`\`\`bash +# Unit tests +npm test + +# Integration tests +npm run test:integration + +# Coverage +npm run test:coverage + +# Security tests +npm run test:security +\`\`\` + +### Test Philosophy +- TDD London School (mock-first) +- Unit tests for business logic +- Integration tests for boundaries +- E2E tests for critical paths +- Security tests for sensitive operations + +### Coverage Requirements +- Minimum 80% line coverage +- 100% coverage for security-critical code +- All public APIs must have tests + +## MCP Integration + +Claude Flow exposes tools via Model Context Protocol: + +\`\`\`bash +# Start MCP server +npx ruflo mcp start + +# List available tools +npx ruflo mcp tools +\`\`\` + +### Available Tools + +| Tool | Purpose | Example | +|------|---------|---------| +| \`swarm_init\` | Initialize swarm coordination | \`swarm_init({topology: "hierarchical"})\` | +| \`agent_spawn\` | Spawn new agents | \`agent_spawn({type: "coder", name: "dev-1"})\` | +| \`memory_store\` | Store in AgentDB | \`memory_store({key: "pattern", value: "..."})\` | +| \`memory_search\` | Semantic search | \`memory_search({query: "auth patterns"})\` | +| \`task_orchestrate\` | Task coordination | \`task_orchestrate({task: "implement feature"})\` | +| \`neural_train\` | Train neural patterns | \`neural_train({iterations: 10})\` | +| \`benchmark_run\` | Performance benchmarks | \`benchmark_run({type: "all"})\` | + +## Hooks System + +Claude Flow uses hooks for lifecycle automation: + +### Core Hooks + +| Hook | Trigger | Purpose | +|------|---------|---------| +| \`pre-task\` | Before task starts | Get context, load patterns | +| \`post-task\` | After task completes | Record completion, train | +| \`pre-edit\` | Before file changes | Validate, backup | +| \`post-edit\` | After file changes | Train patterns, verify | +| \`pre-command\` | Before shell commands | Security check | +| \`post-command\` | After shell commands | Log results | + +### Session Hooks + +| Hook | Purpose | +|------|---------| +| \`session-start\` | Initialize context, load memory | +| \`session-end\` | Export metrics, consolidate memory | +| \`session-restore\` | Resume from checkpoint | +| \`notify\` | Send notifications | + +### Intelligence Hooks + +| Hook | Purpose | +|------|---------| +| \`route\` | Route task to appropriate agents | +| \`explain\` | Generate explanations | +| \`pretrain\` | Pre-train neural patterns | +| \`build-agents\` | Build specialized agents | +| \`transfer\` | Transfer learning between domains | + +### Example Usage +\`\`\`bash +# Before starting a task +npx @claude-flow/cli hooks pre-task \\ + --description "implementing authentication" + +# After completing a task +npx @claude-flow/cli hooks post-task \\ + --task-id "task-123" \\ + --success true + +# Route a task to agents +npx @claude-flow/cli hooks route \\ + --task "implement OAuth2 login flow" +\`\`\` + +## Background Workers + +12 background workers provide continuous optimization: + +| Worker | Priority | Purpose | +|--------|----------|---------| +| \`ultralearn\` | normal | Deep knowledge acquisition | +| \`optimize\` | high | Performance optimization | +| \`consolidate\` | low | Memory consolidation | +| \`predict\` | normal | Predictive preloading | +| \`audit\` | critical | Security analysis | +| \`map\` | normal | Codebase mapping | +| \`preload\` | low | Resource preloading | +| \`deepdive\` | normal | Deep code analysis | +| \`document\` | normal | Auto-documentation | +| \`refactor\` | normal | Refactoring suggestions | +| \`benchmark\` | normal | Performance benchmarking | +| \`testgaps\` | normal | Test coverage analysis | + +### Managing Workers +\`\`\`bash +# List workers +npx @claude-flow/cli hooks worker list + +# Trigger specific worker +npx @claude-flow/cli hooks worker dispatch --trigger audit + +# Check worker status +npx @claude-flow/cli hooks worker status +\`\`\` + +## Intelligence System + +The RuVector Intelligence System provides neural learning: + +### Components +- **SONA**: Self-Optimizing Neural Architecture (<0.05ms adaptation) +- **MoE**: Mixture of Experts for specialized routing +- **HNSW**: Hierarchical Navigable Small World for fast search +- **EWC++**: Elastic Weight Consolidation (prevents forgetting) +- **Flash Attention**: Optimized attention mechanism + +### 4-Step Pipeline +1. **RETRIEVE** - Fetch relevant patterns via HNSW +2. **JUDGE** - Evaluate with verdicts (success/failure) +3. **DISTILL** - Extract key learnings via LoRA +4. **CONSOLIDATE** - Prevent catastrophic forgetting via EWC++ + +## Debugging + +### Log Levels +\`\`\`bash +# Set log level +export CLAUDE_FLOW_LOG_LEVEL=debug + +# Enable verbose mode +npx @claude-flow/cli --verbose +\`\`\` + +### Health Checks +\`\`\`bash +# Run diagnostics +npx @claude-flow/cli doctor --fix + +# Check system status +npx @claude-flow/cli status +\`\`\` +" +`; + +exports[`single-host AGENTS.md is unchanged (#2638) > generateAgentsMd(minimal) 1`] = ` +"# snapshot-project + +> A Claude Flow powered project + +## Quick Start + +### Setup +\`\`\`bash +npm install && npm run build +\`\`\` + +### Test +\`\`\`bash +npm test +\`\`\` + +## Agent Behavior + +### Code Standards +- Keep files under 500 lines +- No hardcoded secrets or credentials +- Validate input at system boundaries +- Use typed interfaces for public APIs + +### File Organization +- \`/src\` - Source code files +- \`/tests\` - Test files +- \`/docs\` - Documentation +- \`/config\` - Configuration files + +## Skills + +| Skill | Purpose | +|-------|---------| +| \`$swarm-orchestration\` | Multi-agent coordination for complex tasks | +| \`$memory-management\` | Pattern storage and semantic search | + +## Security Rules + +- NEVER commit .env files or secrets +- Always validate user inputs +- Prevent directory traversal attacks +- Use parameterized queries for databases +- Sanitize output to prevent XSS + +## Ruflo + Codex Automated Workflow + +Ruflo is the coordination ledger and policy decision point; Codex workers execute code, tests, and commands. A Ruflo coordination call records work but never replaces implementation. + +Use \`guidance_brain({ mode: "recommend", task: "..." })\` when the task can +benefit from Ruflo-specific capabilities. Its live registry is authoritative +for tool presence; registration alone does not prove configuration, +reachability, health, or authorization. If it is not registered, use compatible +\`guidance_recommend\`, CLI discovery, and repository instructions. + +1. **Recall** — search AgentDB memory and relevant ADRs for patterns and constraints. +2. **Inspect** — read source, runtime, dependency, policy, and health state. +3. **Route** — choose the smallest capable topology, agents, skills, and tools. +4. **Plan** — define acceptance criteria, safety envelope, ownership, and validation. +5. **Execute** — Codex workers implement in isolated scopes; Ruflo records coordination. +6. **Test** — run focused tests, regression tests, and failure-path checks. +7. **Validate** — check types, security, policy, compatibility, and artifact integrity. +8. **Benchmark** — compare a source-bound candidate with a source-bound baseline. +9. **Optimize** — improve measured bottlenecks without weakening the safety envelope. +10. **Receipt** — bind claims, evidence, and decisions to exact source/build inputs. +11. **Handoff** — reconcile concurrent work and disclose unresolved limitations. +12. **Publish** — only an independently authorized release gate may publish immutable artifacts. + +### Concurrency and authority invariants + +- Never allow two writers in one worktree. +- Read-only research agents may share a checkout; writing agents may not. +- A child may drop capabilities but can never add tools, servers, namespaces, network access, spend, concurrency, or delegation depth. +- Cancel dependent and not-yet-started sibling work when policy denies an action or a required dependency fails. +- MetaHarness may benchmark candidates concurrently, but it cannot promote, serve, or expand its own SafetyEnvelope. +- Only the integration agent changes shared manifests or lockfiles. +- Do not auto-commit, push, merge, release, or delete worktrees unless the user authorized that operation. +- Every consequential action must produce a policy decision receipt; production, destructive, spend, and promotion actions may require human approval. + +### Repository harness adapter + +When tracked repository instructions define a local collaboration harness: + +1. Assign the isolated worktree before starting a writing session. +2. Start or register the session, inspect current claims, and acquire only the + exact paths, resources, and development ports needed for the task. +3. Renew leases during long work, check acknowledged inbox messages at integration + boundaries, and release claims when handing off or ending. +4. Record focused and integration evidence against the exact source state, + then let the designated integration owner decide release. + +A repository lease coordinates ownership; it does not grant authorization. +In-memory reference adapters demonstrate semantics but are not distributed, +restart-durable release authorities. +The worker still needs the current ADR-324/325 action capability and fencing +epoch for every protected side effect. Heartbeat and lease expiry establish +liveness; a PID is diagnostic only. HEAD alone is not an exact source-state +identity when tracked or untracked changes exist, so a release receipt must +bind a clean commit or an immutable snapshot including those changes. + + +## Links + +- Documentation: https://github.com/ruvnet/ruflo +" +`; diff --git a/v3/@claude-flow/codex/tests/dual-instructions-2638.test.ts b/v3/@claude-flow/codex/tests/dual-instructions-2638.test.ts new file mode 100644 index 0000000000..f0098e68bb --- /dev/null +++ b/v3/@claude-flow/codex/tests/dual-instructions-2638.test.ts @@ -0,0 +1,86 @@ +/** + * #2638 — dual projects get one instruction source: AGENTS.md carries the + * shared sections once, CLAUDE.md imports it with `@AGENTS.md`. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { CodexInitializer } from '../src/initializer.js'; +import { generateDualAgentsMd } from '../src/generators/dual-instructions.js'; +import { generateSharedInstructions, importsAgentsMd } from '../src/generators/shared-instructions.js'; + +const headings = (md: string) => md.split('\n').filter((l) => /^#{2,3} /.test(l)); +const h2 = (md: string) => md.split('\n').filter((l) => /^## /.test(l)); + +describe('generateDualAgentsMd', () => { + const md = generateDualAgentsMd({ projectName: 'demo' }); + + it('carries every shared section verbatim', () => { + for (const section of generateSharedInstructions()) expect(md).toContain(section); + }); + + it('repeats no section heading', () => { + const hs = h2(md); + expect(new Set(hs).size).toBe(hs.length); + }); + + it('keeps the Codex-only sections', () => { + for (const h of ['## Quick Start', '## Codex Execution Model', '## Ruflo + Codex Automated Workflow', '## Commit Messages', '## Path Security', '## Links']) { + expect(md).toContain(h); + } + expect(md).toContain('$swarm-orchestration'); + }); +}); + +describe('CodexInitializer --dual', () => { + let dir: string; + let originalPath: string | undefined; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'dual-2638-')); + originalPath = process.env.PATH; + process.env.PATH = ''; + }); + afterEach(() => { + if (originalPath === undefined) delete process.env.PATH; + else process.env.PATH = originalPath; + rmSync(dir, { recursive: true, force: true }); + }); + + it('writes AGENTS.md as the single source and CLAUDE.md as the @AGENTS.md import', async () => { + const result = await new CodexInitializer().initialize({ projectPath: dir, template: 'default', dual: true }); + expect(result.success).toBe(true); + + const agents = readFileSync(join(dir, 'AGENTS.md'), 'utf-8'); + const claude = readFileSync(join(dir, 'CLAUDE.md'), 'utf-8'); + for (const section of generateSharedInstructions()) expect(agents).toContain(section); + expect(importsAgentsMd(claude)).toBe(true); + + // No section appears in both files. + const shared = headings(claude).filter((h) => headings(agents).includes(h)); + expect(shared).toEqual([]); + for (const section of generateSharedInstructions()) expect(claude).not.toContain(section); + }); + + it('never overwrites a user CLAUDE.md without --force, and says how to migrate', async () => { + writeFileSync(join(dir, 'CLAUDE.md'), '# My rules\n\n- keep me\n', 'utf-8'); + const result = await new CodexInitializer().initialize({ projectPath: dir, template: 'minimal', dual: true }); + expect(result.success).toBe(true); + expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toBe('# My rules\n\n- keep me\n'); + expect(result.filesCreated).not.toContain('CLAUDE.md'); + expect(result.warnings.join('\n')).toMatch(/@AGENTS\.md/); + }); + + it('leaves a CLAUDE.md that already imports AGENTS.md alone, even with --force', async () => { + const mine = '# Ruflo — Claude Code Configuration\n\n@AGENTS.md\n\n## Claude Code Rules\n\n- custom\n'; + writeFileSync(join(dir, 'CLAUDE.md'), mine, 'utf-8'); + const result = await new CodexInitializer().initialize({ projectPath: dir, template: 'minimal', dual: true, force: true }); + expect(result.success).toBe(true); + expect(readFileSync(join(dir, 'CLAUDE.md'), 'utf-8')).toBe(mine); + }); + + it('does not write CLAUDE.md without --dual', async () => { + await new CodexInitializer().initialize({ projectPath: dir, template: 'minimal' }); + expect(existsSync(join(dir, 'CLAUDE.md'))).toBe(false); + }); +}); diff --git a/v3/@claude-flow/codex/tests/single-host-agents-md-snapshot-2638.test.ts b/v3/@claude-flow/codex/tests/single-host-agents-md-snapshot-2638.test.ts new file mode 100644 index 0000000000..5990f9a876 --- /dev/null +++ b/v3/@claude-flow/codex/tests/single-host-agents-md-snapshot-2638.test.ts @@ -0,0 +1,51 @@ +/** + * #2638 — single-host AGENTS.md output must not change. + * + * The snapshot was recorded on origin/main before the dual-mode single-source + * work landed. Dual mode (`--dual`) gets its own composition; a Codex-only + * init keeps writing exactly these bytes. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { generateAgentsMd } from '../src/generators/index.js'; +import { CodexInitializer } from '../src/initializer.js'; +import type { AgentsMdTemplate } from '../src/types.js'; + +const TEMPLATES: AgentsMdTemplate[] = ['minimal', 'default', 'full', 'enterprise']; + +describe('single-host AGENTS.md is unchanged (#2638)', () => { + for (const template of TEMPLATES) { + it(`generateAgentsMd(${template})`, async () => { + const md = await generateAgentsMd({ projectName: 'snapshot-project', template }); + expect(md).toMatchSnapshot(); + }); + } + + describe('CodexInitializer without --dual', () => { + let dir: string; + let originalPath: string | undefined; + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'snapshot-project-')); + // No `codex`/`claude` binaries: MCP registration and plugin install are skipped. + originalPath = process.env.PATH; + process.env.PATH = ''; + }); + afterEach(() => { + if (originalPath === undefined) delete process.env.PATH; + else process.env.PATH = originalPath; + rmSync(dir, { recursive: true, force: true }); + }); + + for (const template of ['minimal', 'default'] as const) { + it(`writes the same AGENTS.md and no CLAUDE.md (${template})`, async () => { + const result = await new CodexInitializer().initialize({ projectPath: dir, template }); + expect(result.success).toBe(true); + const agents = readFileSync(join(dir, 'AGENTS.md'), 'utf-8').split(dir.split('/').pop()!).join(''); + expect(agents).toMatchSnapshot(); + expect(result.filesCreated).not.toContain('CLAUDE.md'); + }); + } + }); +});