@sparkleideas/ruv-swarm 1.0.18-patch.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +1565 -0
  2. package/bin/ruv-swarm-clean.js +1872 -0
  3. package/bin/ruv-swarm-memory.js +119 -0
  4. package/bin/ruv-swarm-secure-heartbeat.js +1549 -0
  5. package/bin/ruv-swarm-secure.js +1689 -0
  6. package/package.json +221 -0
  7. package/src/agent.ts +342 -0
  8. package/src/benchmark.js +267 -0
  9. package/src/claude-flow-enhanced.js +839 -0
  10. package/src/claude-integration/advanced-commands.js +561 -0
  11. package/src/claude-integration/core.js +112 -0
  12. package/src/claude-integration/docs.js +1548 -0
  13. package/src/claude-integration/env-template.js +39 -0
  14. package/src/claude-integration/index.js +209 -0
  15. package/src/claude-integration/remote.js +408 -0
  16. package/src/cli-diagnostics.js +364 -0
  17. package/src/cognitive-pattern-evolution.js +1317 -0
  18. package/src/daa-cognition.js +977 -0
  19. package/src/daa-service.d.ts +298 -0
  20. package/src/daa-service.js +1116 -0
  21. package/src/diagnostics.js +533 -0
  22. package/src/errors.js +528 -0
  23. package/src/github-coordinator/README.md +193 -0
  24. package/src/github-coordinator/claude-hooks.js +162 -0
  25. package/src/github-coordinator/gh-cli-coordinator.js +260 -0
  26. package/src/hooks/cli.js +82 -0
  27. package/src/hooks/index.js +1900 -0
  28. package/src/index-enhanced.d.ts +371 -0
  29. package/src/index-enhanced.js +734 -0
  30. package/src/index.d.ts +287 -0
  31. package/src/index.js +405 -0
  32. package/src/index.ts +457 -0
  33. package/src/logger.js +182 -0
  34. package/src/logging-config.js +179 -0
  35. package/src/mcp-daa-tools.js +735 -0
  36. package/src/mcp-tools-benchmarks.js +328 -0
  37. package/src/mcp-tools-enhanced.js +2863 -0
  38. package/src/memory-config.js +42 -0
  39. package/src/meta-learning-framework.js +1359 -0
  40. package/src/neural-agent.js +830 -0
  41. package/src/neural-coordination-protocol.js +1363 -0
  42. package/src/neural-models/README.md +118 -0
  43. package/src/neural-models/autoencoder.js +543 -0
  44. package/src/neural-models/base.js +269 -0
  45. package/src/neural-models/cnn.js +497 -0
  46. package/src/neural-models/gnn.js +447 -0
  47. package/src/neural-models/gru.js +536 -0
  48. package/src/neural-models/index.js +273 -0
  49. package/src/neural-models/lstm.js +551 -0
  50. package/src/neural-models/neural-presets-complete.js +1306 -0
  51. package/src/neural-models/presets/graph.js +392 -0
  52. package/src/neural-models/presets/index.js +279 -0
  53. package/src/neural-models/presets/nlp.js +328 -0
  54. package/src/neural-models/presets/timeseries.js +368 -0
  55. package/src/neural-models/presets/vision.js +387 -0
  56. package/src/neural-models/resnet.js +534 -0
  57. package/src/neural-models/transformer.js +515 -0
  58. package/src/neural-models/vae.js +489 -0
  59. package/src/neural-network-manager.js +1938 -0
  60. package/src/neural-network.ts +296 -0
  61. package/src/neural.js +574 -0
  62. package/src/performance-benchmarks.js +898 -0
  63. package/src/performance.js +458 -0
  64. package/src/persistence-pooled.js +695 -0
  65. package/src/persistence.js +480 -0
  66. package/src/schemas.js +864 -0
  67. package/src/security.js +218 -0
  68. package/src/singleton-container.js +183 -0
  69. package/src/sqlite-pool.js +587 -0
  70. package/src/sqlite-worker.js +141 -0
  71. package/src/types.ts +164 -0
  72. package/src/utils.ts +286 -0
  73. package/src/wasm-loader.js +601 -0
  74. package/src/wasm-loader2.js +404 -0
  75. package/src/wasm-memory-optimizer.js +783 -0
  76. package/src/wasm-types.d.ts +63 -0
  77. package/wasm/README.md +347 -0
  78. package/wasm/neuro-divergent.wasm +0 -0
  79. package/wasm/package.json +18 -0
  80. package/wasm/ruv-fann.wasm +0 -0
  81. package/wasm/ruv_swarm_simd.wasm +0 -0
  82. package/wasm/ruv_swarm_wasm.d.ts +391 -0
  83. package/wasm/ruv_swarm_wasm.js +2164 -0
  84. package/wasm/ruv_swarm_wasm_bg.wasm +0 -0
  85. package/wasm/ruv_swarm_wasm_bg.wasm.d.ts +123 -0
  86. package/wasm/wasm-bindings-loader.mjs +435 -0
  87. package/wasm/wasm-updates.md +684 -0
@@ -0,0 +1,1548 @@
1
+ /**
2
+ * Documentation generation module for Claude Code integration
3
+ * Generates claude.md and .claude/commands/ documentation
4
+ */
5
+
6
+ import fs from 'fs/promises';
7
+ import path from 'path';
8
+ import { AdvancedCommandsGenerator } from './advanced-commands.js';
9
+
10
+ class ClaudeDocsGenerator {
11
+ constructor(options = {}) {
12
+ this.workingDir = options.workingDir || process.cwd();
13
+ this.advancedGenerator = new AdvancedCommandsGenerator(options);
14
+ }
15
+
16
+ /**
17
+ * Generate main claude.md configuration file with protection
18
+ */
19
+ async generateClaudeMd(options = {}) {
20
+ const { force = false, merge = false, backup = false, noBackup = false, interactive = true } = options;
21
+
22
+ // Check if CLAUDE.md already exists
23
+ const filePath = path.join(this.workingDir, 'CLAUDE.md');
24
+ const fileExists = await this.fileExists(filePath);
25
+
26
+ if (fileExists && !force && !merge && !backup) {
27
+ if (interactive) {
28
+ // Interactive prompt for action
29
+ const action = await this.promptUserAction(filePath);
30
+ if (action === 'cancel') {
31
+ throw new Error('CLAUDE.md generation cancelled by user');
32
+ } else if (action === 'overwrite') {
33
+ await this.createBackup(filePath);
34
+ } else if (action === 'merge') {
35
+ return await this.mergeClaudeMd(filePath);
36
+ }
37
+ } else {
38
+ // Non-interactive mode - fail safely
39
+ throw new Error('CLAUDE.md already exists. Use --force to overwrite, --backup to backup existing, or --merge to combine.');
40
+ }
41
+ } else if (fileExists && force) {
42
+ // Force flag: overwrite with optional backup creation
43
+ if (!noBackup) {
44
+ await this.createBackup(filePath);
45
+ console.log('📄 Backing up existing CLAUDE.md before force overwrite');
46
+ } else {
47
+ console.log('⚠️ Force overwriting existing CLAUDE.md (no backup - disabled by --no-backup)');
48
+ }
49
+ } else if (fileExists && backup && !force && !merge) {
50
+ // Backup flag: create backup then overwrite
51
+ await this.createBackup(filePath);
52
+ console.log('📄 Backing up existing CLAUDE.md before overwriting');
53
+ } else if (fileExists && merge) {
54
+ // Merge with existing content (backup first if backup flag is set)
55
+ if (backup) {
56
+ await this.createBackup(filePath);
57
+ }
58
+ return await this.mergeClaudeMd(filePath, noBackup);
59
+ }
60
+ const content = `# Claude Code Configuration for @sparkleideas/ruv-swarm
61
+
62
+ ## 🎯 IMPORTANT: Separation of Responsibilities
63
+
64
+ ### Claude Code Handles:
65
+ - ✅ **ALL file operations** (Read, Write, Edit, MultiEdit)
66
+ - ✅ **ALL code generation** and development tasks
67
+ - ✅ **ALL bash commands** and system operations
68
+ - ✅ **ALL actual implementation** work
69
+ - ✅ **Project navigation** and code analysis
70
+
71
+ ### @sparkleideas/ruv-swarm MCP Tools Handle:
72
+ - 🧠 **Coordination only** - Orchestrating Claude Code's actions
73
+ - 💾 **Memory management** - Persistent state across sessions
74
+ - 🤖 **Neural features** - Cognitive patterns and learning
75
+ - 📊 **Performance tracking** - Monitoring and metrics
76
+ - 🐝 **Swarm orchestration** - Multi-agent coordination
77
+
78
+ ### ⚠️ Key Principle:
79
+ **MCP tools DO NOT create content or write code.** They coordinate and enhance Claude Code's native capabilities. Think of them as an orchestration layer that helps Claude Code work more efficiently.
80
+
81
+ ## 🚀 CRITICAL: Parallel Execution & Batch Operations
82
+
83
+ ### 🚨 MANDATORY RULE #1: BATCH EVERYTHING
84
+
85
+ **When using swarms, you MUST use BatchTool for ALL operations:**
86
+
87
+ 1. **NEVER** send multiple messages for related operations
88
+ 2. **ALWAYS** combine multiple tool calls in ONE message
89
+ 3. **PARALLEL** execution is MANDATORY, not optional
90
+
91
+ ### ⚡ THE GOLDEN RULE OF SWARMS
92
+
93
+ \`\`\`
94
+ If you need to do X operations, they should be in 1 message, not X messages
95
+ \`\`\`
96
+
97
+ ### 📦 BATCH TOOL EXAMPLES
98
+
99
+ **✅ CORRECT - Everything in ONE Message:**
100
+ \`\`\`javascript
101
+ [Single Message with BatchTool]:
102
+ mcp__ruv-swarm__swarm_init { topology: "mesh", maxAgents: 6 }
103
+ mcp__ruv-swarm__agent_spawn { type: "researcher" }
104
+ mcp__ruv-swarm__agent_spawn { type: "coder" }
105
+ mcp__ruv-swarm__agent_spawn { type: "analyst" }
106
+ mcp__ruv-swarm__agent_spawn { type: "tester" }
107
+ mcp__ruv-swarm__agent_spawn { type: "coordinator" }
108
+ TodoWrite { todos: [todo1, todo2, todo3, todo4, todo5] }
109
+ Bash "mkdir -p app/{src,tests,docs}"
110
+ Write "app/package.json"
111
+ Write "app/README.md"
112
+ Write "app/src/index.js"
113
+ \`\`\`
114
+
115
+ **❌ WRONG - Multiple Messages (NEVER DO THIS):**
116
+ \`\`\`javascript
117
+ Message 1: mcp__ruv-swarm__swarm_init
118
+ Message 2: mcp__ruv-swarm__agent_spawn
119
+ Message 3: mcp__ruv-swarm__agent_spawn
120
+ Message 4: TodoWrite (one todo)
121
+ Message 5: Bash "mkdir src"
122
+ Message 6: Write "package.json"
123
+ // This is 6x slower and breaks parallel coordination!
124
+ \`\`\`
125
+
126
+ ### 🎯 BATCH OPERATIONS BY TYPE
127
+
128
+ **File Operations (Single Message):**
129
+ - Read 10 files? → One message with 10 Read calls
130
+ - Write 5 files? → One message with 5 Write calls
131
+ - Edit 1 file many times? → One MultiEdit call
132
+
133
+ **Swarm Operations (Single Message):**
134
+ - Need 8 agents? → One message with swarm_init + 8 agent_spawn calls
135
+ - Multiple memories? → One message with all memory_usage calls
136
+ - Task + monitoring? → One message with task_orchestrate + swarm_monitor
137
+
138
+ **Command Operations (Single Message):**
139
+ - Multiple directories? → One message with all mkdir commands
140
+ - Install + test + lint? → One message with all npm commands
141
+ - Git operations? → One message with all git commands
142
+
143
+ ## 🚀 Quick Setup (Stdio MCP - Recommended)
144
+
145
+ ### 1. Add MCP Server (Stdio - No Port Needed)
146
+ \`\`\`bash
147
+ # Add @sparkleideas/ruv-swarm MCP server to Claude Code using stdio
148
+ claude mcp add @sparkleideas/ruv-swarm npx @sparkleideas/ruv-swarm mcp start
149
+ \`\`\`
150
+
151
+ ### 2. Use MCP Tools for Coordination in Claude Code
152
+ Once configured, @sparkleideas/ruv-swarm MCP tools enhance Claude Code's coordination:
153
+
154
+ **Initialize a swarm:**
155
+ - Use the \`mcp__ruv-swarm__swarm_init\` tool to set up coordination topology
156
+ - Choose: mesh, hierarchical, ring, or star
157
+ - This creates a coordination framework for Claude Code's work
158
+
159
+ **Spawn agents:**
160
+ - Use \`mcp__ruv-swarm__agent_spawn\` tool to create specialized coordinators
161
+ - Agent types represent different thinking patterns, not actual coders
162
+ - They help Claude Code approach problems from different angles
163
+
164
+ **Orchestrate tasks:**
165
+ - Use \`mcp__ruv-swarm__task_orchestrate\` tool to coordinate complex workflows
166
+ - This breaks down tasks for Claude Code to execute systematically
167
+ - The agents don't write code - they coordinate Claude Code's actions
168
+
169
+ ## Available MCP Tools for Coordination
170
+
171
+ ### Coordination Tools:
172
+ - \`mcp__ruv-swarm__swarm_init\` - Set up coordination topology for Claude Code
173
+ - \`mcp__ruv-swarm__agent_spawn\` - Create cognitive patterns to guide Claude Code
174
+ - \`mcp__ruv-swarm__task_orchestrate\` - Break down and coordinate complex tasks
175
+
176
+ ### Monitoring Tools:
177
+ - \`mcp__ruv-swarm__swarm_status\` - Monitor coordination effectiveness
178
+ - \`mcp__ruv-swarm__agent_list\` - View active cognitive patterns
179
+ - \`mcp__ruv-swarm__agent_metrics\` - Track coordination performance
180
+ - \`mcp__ruv-swarm__task_status\` - Check workflow progress
181
+ - \`mcp__ruv-swarm__task_results\` - Review coordination outcomes
182
+
183
+ ### Memory & Neural Tools:
184
+ - \`mcp__ruv-swarm__memory_usage\` - Persistent memory across sessions
185
+ - \`mcp__ruv-swarm__neural_status\` - Neural pattern effectiveness
186
+ - \`mcp__ruv-swarm__neural_train\` - Improve coordination patterns
187
+ - \`mcp__ruv-swarm__neural_patterns\` - Analyze thinking approaches
188
+
189
+ ### System Tools:
190
+ - \`mcp__ruv-swarm__benchmark_run\` - Measure coordination efficiency
191
+ - \`mcp__ruv-swarm__features_detect\` - Available capabilities
192
+ - \`mcp__ruv-swarm__swarm_monitor\` - Real-time coordination tracking
193
+
194
+ ## Workflow Examples (Coordination-Focused)
195
+
196
+ ### Research Coordination Example
197
+ **Context:** Claude Code needs to research a complex topic systematically
198
+
199
+ **Step 1:** Set up research coordination
200
+ - Tool: \`mcp__ruv-swarm__swarm_init\`
201
+ - Parameters: \`{"topology": "mesh", "maxAgents": 5, "strategy": "balanced"}\`
202
+ - Result: Creates a mesh topology for comprehensive exploration
203
+
204
+ **Step 2:** Define research perspectives
205
+ - Tool: \`mcp__ruv-swarm__agent_spawn\`
206
+ - Parameters: \`{"type": "researcher", "name": "Literature Review"}\`
207
+ - Tool: \`mcp__ruv-swarm__agent_spawn\`
208
+ - Parameters: \`{"type": "analyst", "name": "Data Analysis"}\`
209
+ - Result: Different cognitive patterns for Claude Code to use
210
+
211
+ **Step 3:** Coordinate research execution
212
+ - Tool: \`mcp__ruv-swarm__task_orchestrate\`
213
+ - Parameters: \`{"task": "Research neural architecture search papers", "strategy": "adaptive"}\`
214
+ - Result: Claude Code systematically searches, reads, and analyzes papers
215
+
216
+ **What Actually Happens:**
217
+ 1. The swarm sets up a coordination framework
218
+ 2. Each agent MUST use @sparkleideas/ruv-swarm hooks for coordination:
219
+ - \`npx @sparkleideas/ruv-swarm hook pre-task\` before starting
220
+ - \`npx @sparkleideas/ruv-swarm hook post-edit\` after each file operation
221
+ - \`npx @sparkleideas/ruv-swarm hook notification\` to share decisions
222
+ 3. Claude Code uses its native Read, WebSearch, and Task tools
223
+ 4. The swarm coordinates through shared memory and hooks
224
+ 5. Results are synthesized by Claude Code with full coordination history
225
+
226
+ ### Development Coordination Example
227
+ **Context:** Claude Code needs to build a complex system with multiple components
228
+
229
+ **Step 1:** Set up development coordination
230
+ - Tool: \`mcp__ruv-swarm__swarm_init\`
231
+ - Parameters: \`{"topology": "hierarchical", "maxAgents": 8, "strategy": "specialized"}\`
232
+ - Result: Hierarchical structure for organized development
233
+
234
+ **Step 2:** Define development perspectives
235
+ - Tool: \`mcp__ruv-swarm__agent_spawn\`
236
+ - Parameters: \`{"type": "architect", "name": "System Design"}\`
237
+ - Result: Architectural thinking pattern for Claude Code
238
+
239
+ **Step 3:** Coordinate implementation
240
+ - Tool: \`mcp__ruv-swarm__task_orchestrate\`
241
+ - Parameters: \`{"task": "Implement user authentication with JWT", "strategy": "parallel"}\`
242
+ - Result: Claude Code implements features using its native tools
243
+
244
+ **What Actually Happens:**
245
+ 1. The swarm creates a development coordination plan
246
+ 2. Each agent coordinates using mandatory hooks:
247
+ - Pre-task hooks for context loading
248
+ - Post-edit hooks for progress tracking
249
+ - Memory storage for cross-agent coordination
250
+ 3. Claude Code uses Write, Edit, Bash tools for implementation
251
+ 4. Agents share progress through @sparkleideas/ruv-swarm memory
252
+ 5. All code is written by Claude Code with full coordination
253
+
254
+ ## Best Practices for Coordination
255
+
256
+ ### ✅ DO:
257
+ - Use MCP tools to coordinate Claude Code's approach to complex tasks
258
+ - Let the swarm break down problems into manageable pieces
259
+ - Use memory tools to maintain context across sessions
260
+ - Monitor coordination effectiveness with status tools
261
+ - Train neural patterns for better coordination over time
262
+
263
+ ### ❌ DON'T:
264
+ - Expect agents to write code (Claude Code does all implementation)
265
+ - Use MCP tools for file operations (use Claude Code's native tools)
266
+ - Try to make agents execute bash commands (Claude Code handles this)
267
+ - Confuse coordination with execution (MCP coordinates, Claude executes)
268
+
269
+ ## Memory and Persistence
270
+
271
+ The swarm provides persistent memory that helps Claude Code:
272
+ - Remember project context across sessions
273
+ - Track decisions and rationale
274
+ - Maintain consistency in large projects
275
+ - Learn from previous coordination patterns
276
+
277
+ ## Performance Benefits
278
+
279
+ When using @sparkleideas/ruv-swarm coordination with Claude Code:
280
+ - **84.8% SWE-Bench solve rate** - Better problem-solving through coordination
281
+ - **32.3% token reduction** - Efficient task breakdown reduces redundancy
282
+ - **2.8-4.4x speed improvement** - Parallel coordination strategies
283
+ - **27+ neural models** - Diverse cognitive approaches
284
+
285
+ ## Claude Code Hooks Integration
286
+
287
+ @sparkleideas/ruv-swarm includes powerful hooks that automate coordination:
288
+
289
+ ### Pre-Operation Hooks
290
+ - **Auto-assign agents** before file edits based on file type
291
+ - **Validate commands** before execution for safety
292
+ - **Prepare resources** automatically for complex operations
293
+ - **Optimize topology** based on task complexity analysis
294
+ - **Cache searches** for improved performance
295
+
296
+ ### Post-Operation Hooks
297
+ - **Auto-format code** using language-specific formatters
298
+ - **Train neural patterns** from successful operations
299
+ - **Update memory** with operation context
300
+ - **Analyze performance** and identify bottlenecks
301
+ - **Track token usage** for efficiency metrics
302
+
303
+ ### Session Management
304
+ - **Generate summaries** at session end
305
+ - **Persist state** across Claude Code sessions
306
+ - **Track metrics** for continuous improvement
307
+ - **Restore previous** session context automatically
308
+
309
+ ### Advanced Features (New!)
310
+ - **🚀 Automatic Topology Selection** - Optimal swarm structure for each task
311
+ - **⚡ Parallel Execution** - 2.8-4.4x speed improvements
312
+ - **🧠 Neural Training** - Continuous learning from operations
313
+ - **📊 Bottleneck Analysis** - Real-time performance optimization
314
+ - **🤖 Smart Auto-Spawning** - Zero manual agent management
315
+ - **🛡️ Self-Healing Workflows** - Automatic error recovery
316
+ - **💾 Cross-Session Memory** - Persistent learning & context
317
+
318
+ ### Configuration
319
+ Hooks are pre-configured in \`.claude/settings.json\`. Key features:
320
+ - Automatic agent assignment for different file types
321
+ - Code formatting on save
322
+ - Neural pattern learning from edits
323
+ - Session state persistence
324
+ - Performance tracking and optimization
325
+ - Intelligent caching and token reduction
326
+
327
+ See \`.claude/commands/\` for detailed documentation on all features.
328
+
329
+ ## Integration Tips
330
+
331
+ 1. **Start Simple**: Begin with basic swarm init and single agent
332
+ 2. **Scale Gradually**: Add more agents as task complexity increases
333
+ 3. **Use Memory**: Store important decisions and context
334
+ 4. **Monitor Progress**: Regular status checks ensure effective coordination
335
+ 5. **Train Patterns**: Let neural agents learn from successful coordinations
336
+ 6. **Enable Hooks**: Use the pre-configured hooks for automation
337
+
338
+ ## 🧠 SWARM ORCHESTRATION PATTERN
339
+
340
+ ### You are the SWARM ORCHESTRATOR. **IMMEDIATELY SPAWN AGENTS IN PARALLEL** to execute tasks
341
+
342
+ ### 🚨 CRITICAL INSTRUCTION: You are the SWARM ORCHESTRATOR
343
+
344
+ **MANDATORY**: When using swarms, you MUST:
345
+ 1. **SPAWN ALL AGENTS IN ONE BATCH** - Use multiple tool calls in a SINGLE message
346
+ 2. **EXECUTE TASKS IN PARALLEL** - Never wait for one task before starting another
347
+ 3. **USE BATCHTOOL FOR EVERYTHING** - Multiple operations = Single message with multiple tools
348
+ 4. **ALL AGENTS MUST USE COORDINATION TOOLS** - Every spawned agent MUST use @sparkleideas/ruv-swarm hooks and memory
349
+
350
+ ## 📋 MANDATORY AGENT COORDINATION PROTOCOL
351
+
352
+ ### 🔴 CRITICAL: Every Agent MUST Follow This Protocol
353
+
354
+ When you spawn an agent using the Task tool, that agent MUST:
355
+
356
+ **1️⃣ BEFORE Starting Work:**
357
+ \`\`\`bash
358
+ # Check previous work and load context
359
+ npx @sparkleideas/ruv-swarm hook pre-task --description "[agent task]" --auto-spawn-agents false
360
+ npx @sparkleideas/ruv-swarm hook session-restore --session-id "swarm-[id]" --load-memory true
361
+ \`\`\`
362
+
363
+ **2️⃣ DURING Work (After EVERY Major Step):**
364
+ \`\`\`bash
365
+ # Store progress in memory after each file operation
366
+ npx @sparkleideas/ruv-swarm hook post-edit --file "[filepath]" --memory-key "swarm/[agent]/[step]"
367
+
368
+ # Store decisions and findings
369
+ npx @sparkleideas/ruv-swarm hook notification --message "[what was done]" --telemetry true
370
+
371
+ # Check coordination with other agents
372
+ npx @sparkleideas/ruv-swarm hook pre-search --query "[what to check]" --cache-results true
373
+ \`\`\`
374
+
375
+ **3️⃣ AFTER Completing Work:**
376
+ \`\`\`bash
377
+ # Save all results and learnings
378
+ npx @sparkleideas/ruv-swarm hook post-task --task-id "[task]" --analyze-performance true
379
+ npx @sparkleideas/ruv-swarm hook session-end --export-metrics true --generate-summary true
380
+ \`\`\`
381
+
382
+ ### 🎯 AGENT PROMPT TEMPLATE
383
+
384
+ When spawning agents, ALWAYS include these coordination instructions:
385
+
386
+ \`\`\`
387
+ You are the [Agent Type] agent in a coordinated swarm.
388
+
389
+ MANDATORY COORDINATION:
390
+ 1. START: Run \`npx @sparkleideas/ruv-swarm hook pre-task --description "[your task]"\`
391
+ 2. DURING: After EVERY file operation, run \`npx @sparkleideas/ruv-swarm hook post-edit --file "[file]" --memory-key "agent/[step]"\`
392
+ 3. MEMORY: Store ALL decisions using \`npx @sparkleideas/ruv-swarm hook notification --message "[decision]"\`
393
+ 4. END: Run \`npx @sparkleideas/ruv-swarm hook post-task --task-id "[task]" --analyze-performance true\`
394
+
395
+ Your specific task: [detailed task description]
396
+
397
+ REMEMBER: Coordinate with other agents by checking memory BEFORE making decisions!
398
+ \`\`\`
399
+
400
+ ### ⚡ PARALLEL EXECUTION IS MANDATORY
401
+
402
+ **THIS IS WRONG ❌ (Sequential - NEVER DO THIS):**
403
+ \`\`\`
404
+ Message 1: Initialize swarm
405
+ Message 2: Spawn agent 1
406
+ Message 3: Spawn agent 2
407
+ Message 4: Create file 1
408
+ Message 5: Create file 2
409
+ \`\`\`
410
+
411
+ **THIS IS CORRECT ✅ (Parallel - ALWAYS DO THIS):**
412
+ \`\`\`
413
+ Message 1: [BatchTool]
414
+ - mcp__ruv-swarm__swarm_init
415
+ - mcp__ruv-swarm__agent_spawn (researcher)
416
+ - mcp__ruv-swarm__agent_spawn (coder)
417
+ - mcp__ruv-swarm__agent_spawn (analyst)
418
+ - mcp__ruv-swarm__agent_spawn (tester)
419
+ - mcp__ruv-swarm__agent_spawn (coordinator)
420
+
421
+ Message 2: [BatchTool]
422
+ - Write file1.js
423
+ - Write file2.js
424
+ - Write file3.js
425
+ - Bash mkdir commands
426
+ - TodoWrite updates
427
+ \`\`\`
428
+
429
+ ### 🎯 MANDATORY SWARM PATTERN
430
+
431
+ When given ANY complex task with swarms:
432
+
433
+ \`\`\`
434
+ STEP 1: IMMEDIATE PARALLEL SPAWN (Single Message!)
435
+ [BatchTool]:
436
+ - mcp__ruv-swarm__swarm_init { topology: "hierarchical", maxAgents: 8, strategy: "parallel" }
437
+ - mcp__ruv-swarm__agent_spawn { type: "architect", name: "System Designer" }
438
+ - mcp__ruv-swarm__agent_spawn { type: "coder", name: "API Developer" }
439
+ - mcp__ruv-swarm__agent_spawn { type: "coder", name: "Frontend Dev" }
440
+ - mcp__ruv-swarm__agent_spawn { type: "analyst", name: "DB Designer" }
441
+ - mcp__ruv-swarm__agent_spawn { type: "tester", name: "QA Engineer" }
442
+ - mcp__ruv-swarm__agent_spawn { type: "researcher", name: "Tech Lead" }
443
+ - mcp__ruv-swarm__agent_spawn { type: "coordinator", name: "PM" }
444
+ - TodoWrite { todos: [multiple todos at once] }
445
+
446
+ STEP 2: PARALLEL TASK EXECUTION (Single Message!)
447
+ [BatchTool]:
448
+ - mcp__ruv-swarm__task_orchestrate { task: "main task", strategy: "parallel" }
449
+ - mcp__ruv-swarm__memory_usage { action: "store", key: "init", value: {...} }
450
+ - Multiple Read operations
451
+ - Multiple Write operations
452
+ - Multiple Bash commands
453
+
454
+ STEP 3: CONTINUE PARALLEL WORK (Never Sequential!)
455
+ \`\`\`
456
+
457
+ ### 📊 VISUAL TASK TRACKING FORMAT
458
+
459
+ Use this format when displaying task progress:
460
+
461
+ \`\`\`
462
+ 📊 Progress Overview
463
+ ├── Total Tasks: X
464
+ ├── ✅ Completed: X (X%)
465
+ ├── 🔄 In Progress: X (X%)
466
+ ├── ⭕ Todo: X (X%)
467
+ └── ❌ Blocked: X (X%)
468
+
469
+ 📋 Todo (X)
470
+ └── 🔴 001: [Task description] [PRIORITY] ▶
471
+
472
+ 🔄 In progress (X)
473
+ ├── 🟡 002: [Task description] ↳ X deps ▶
474
+ └── 🔴 003: [Task description] [PRIORITY] ▶
475
+
476
+ ✅ Completed (X)
477
+ ├── ✅ 004: [Task description]
478
+ └── ... (more completed tasks)
479
+
480
+ Priority indicators: 🔴 HIGH/CRITICAL, 🟡 MEDIUM, 🟢 LOW
481
+ Dependencies: ↳ X deps | Actionable: ▶
482
+ \`\`\`
483
+
484
+ ### 🎯 REAL EXAMPLE: Full-Stack App Development
485
+
486
+ **Task**: "Build a complete REST API with authentication, database, and tests"
487
+
488
+ **🚨 MANDATORY APPROACH - Everything in Parallel:**
489
+
490
+ \`\`\`javascript
491
+ // ✅ CORRECT: SINGLE MESSAGE with ALL operations
492
+ [BatchTool - Message 1]:
493
+ // Initialize and spawn ALL agents at once
494
+ mcp__ruv-swarm__swarm_init { topology: "hierarchical", maxAgents: 8, strategy: "parallel" }
495
+ mcp__ruv-swarm__agent_spawn { type: "architect", name: "System Designer" }
496
+ mcp__ruv-swarm__agent_spawn { type: "coder", name: "API Developer" }
497
+ mcp__ruv-swarm__agent_spawn { type: "coder", name: "Auth Expert" }
498
+ mcp__ruv-swarm__agent_spawn { type: "analyst", name: "DB Designer" }
499
+ mcp__ruv-swarm__agent_spawn { type: "tester", name: "Test Engineer" }
500
+ mcp__ruv-swarm__agent_spawn { type: "coordinator", name: "Lead" }
501
+
502
+ // Update ALL todos at once
503
+ TodoWrite { todos: [
504
+ { id: "design", content: "Design API architecture", status: "in_progress", priority: "high" },
505
+ { id: "auth", content: "Implement authentication", status: "pending", priority: "high" },
506
+ { id: "db", content: "Design database schema", status: "pending", priority: "high" },
507
+ { id: "api", content: "Build REST endpoints", status: "pending", priority: "high" },
508
+ { id: "tests", content: "Write comprehensive tests", status: "pending", priority: "medium" }
509
+ ]}
510
+
511
+ // Start orchestration
512
+ mcp__ruv-swarm__task_orchestrate { task: "Build REST API", strategy: "parallel" }
513
+
514
+ // Store initial memory
515
+ mcp__ruv-swarm__memory_usage { action: "store", key: "project/init", value: { started: Date.now() } }
516
+
517
+ [BatchTool - Message 2]:
518
+ // Create ALL directories at once
519
+ Bash("mkdir -p test-app/{src,tests,docs,config}")
520
+ Bash("mkdir -p test-app/src/{models,routes,middleware,services}")
521
+ Bash("mkdir -p test-app/tests/{unit,integration}")
522
+
523
+ // Write ALL base files at once
524
+ Write("test-app/package.json", packageJsonContent)
525
+ Write("test-app/.env.example", envContent)
526
+ Write("test-app/README.md", readmeContent)
527
+ Write("test-app/src/server.js", serverContent)
528
+ Write("test-app/src/config/database.js", dbConfigContent)
529
+
530
+ [BatchTool - Message 3]:
531
+ // Read multiple files for context
532
+ Read("test-app/package.json")
533
+ Read("test-app/src/server.js")
534
+ Read("test-app/.env.example")
535
+
536
+ // Run multiple commands
537
+ Bash("cd test-app && npm install")
538
+ Bash("cd test-app && npm run lint")
539
+ Bash("cd test-app && npm test")
540
+ \`\`\`
541
+
542
+ ### 🚫 NEVER DO THIS (Sequential = WRONG):
543
+ \`\`\`javascript
544
+ // ❌ WRONG: Multiple messages, one operation each
545
+ Message 1: mcp__ruv-swarm__swarm_init
546
+ Message 2: mcp__ruv-swarm__agent_spawn (just one agent)
547
+ Message 3: mcp__ruv-swarm__agent_spawn (another agent)
548
+ Message 4: TodoWrite (single todo)
549
+ Message 5: Write (single file)
550
+ // This is 5x slower and wastes swarm coordination!
551
+ \`\`\`
552
+
553
+ ### 🔄 MEMORY COORDINATION PATTERN
554
+
555
+ Every agent coordination step MUST use memory:
556
+
557
+ \`\`\`
558
+ // After each major decision or implementation
559
+ mcp__ruv-swarm__memory_usage
560
+ action: "store"
561
+ key: "swarm-{id}/agent-{name}/{step}"
562
+ value: {
563
+ timestamp: Date.now(),
564
+ decision: "what was decided",
565
+ implementation: "what was built",
566
+ nextSteps: ["step1", "step2"],
567
+ dependencies: ["dep1", "dep2"]
568
+ }
569
+
570
+ // To retrieve coordination data
571
+ mcp__ruv-swarm__memory_usage
572
+ action: "retrieve"
573
+ key: "swarm-{id}/agent-{name}/{step}"
574
+
575
+ // To check all swarm progress
576
+ mcp__ruv-swarm__memory_usage
577
+ action: "list"
578
+ pattern: "swarm-{id}/*"
579
+ \`\`\`
580
+
581
+ ### ⚡ PERFORMANCE TIPS
582
+
583
+ 1. **Batch Everything**: Never operate on single files when multiple are needed
584
+ 2. **Parallel First**: Always think "what can run simultaneously?"
585
+ 3. **Memory is Key**: Use memory for ALL cross-agent coordination
586
+ 4. **Monitor Progress**: Use mcp__ruv-swarm__swarm_monitor for real-time tracking
587
+ 5. **Auto-Optimize**: Let hooks handle topology and agent selection
588
+
589
+ ### 🎨 VISUAL SWARM STATUS
590
+
591
+ When showing swarm status, use this format:
592
+
593
+ \`\`\`
594
+ 🐝 Swarm Status: ACTIVE
595
+ ├── 🏗️ Topology: hierarchical
596
+ ├── 👥 Agents: 6/8 active
597
+ ├── ⚡ Mode: parallel execution
598
+ ├── 📊 Tasks: 12 total (4 complete, 6 in-progress, 2 pending)
599
+ └── 🧠 Memory: 15 coordination points stored
600
+
601
+ Agent Activity:
602
+ ├── 🟢 architect: Designing database schema...
603
+ ├── 🟢 coder-1: Implementing auth endpoints...
604
+ ├── 🟢 coder-2: Building user CRUD operations...
605
+ ├── 🟢 analyst: Optimizing query performance...
606
+ ├── 🟡 tester: Waiting for auth completion...
607
+ └── 🟢 coordinator: Monitoring progress...
608
+ \`\`\`
609
+
610
+ ## Support
611
+
612
+ - Documentation: https://github.com/ruvnet/ruv-FANN/tree/main/ruv-swarm
613
+ - Issues: https://github.com/ruvnet/ruv-FANN/issues
614
+ - Examples: https://github.com/ruvnet/ruv-FANN/tree/main/ruv-swarm/examples
615
+
616
+ ---
617
+
618
+ Remember: **@sparkleideas/ruv-swarm coordinates, Claude Code creates!** Start with \`mcp__ruv-swarm__swarm_init\` to enhance your development workflow.
619
+ `;
620
+
621
+ // Write the new content
622
+ await fs.writeFile(filePath, content);
623
+
624
+ // Clean up old backups (keep only last 5)
625
+ await this.cleanupOldBackups(filePath);
626
+
627
+ return { file: 'CLAUDE.md', success: true, action: 'created' };
628
+ }
629
+
630
+ /**
631
+ * Generate command documentation files in organized subdirectories
632
+ */
633
+ async generateCommandDocs() {
634
+ const commandsDir = path.join(this.workingDir, '.claude', 'commands');
635
+ await fs.mkdir(commandsDir, { recursive: true });
636
+
637
+ // Create subdirectories
638
+ const subdirs = ['coordination', 'monitoring', 'memory', 'workflows', 'hooks',
639
+ 'optimization', 'analysis', 'training', 'automation'];
640
+ for (const subdir of subdirs) {
641
+ await fs.mkdir(path.join(commandsDir, subdir), { recursive: true });
642
+ }
643
+
644
+ const commands = {
645
+ // Coordination commands
646
+ 'coordination/init.md': {
647
+ title: 'Initialize Coordination Framework',
648
+ tool: 'mcp__ruv-swarm__swarm_init',
649
+ params: '{"topology": "mesh", "maxAgents": 5, "strategy": "balanced"}',
650
+ description: 'Set up a coordination topology to guide Claude Code\'s approach to complex tasks',
651
+ details: `This tool creates a coordination framework that helps Claude Code:
652
+ - Break down complex problems systematically
653
+ - Approach tasks from multiple perspectives
654
+ - Maintain consistency across large projects
655
+ - Work more efficiently through structured coordination
656
+
657
+ Remember: This does NOT create actual coding agents. It creates a coordination pattern for Claude Code to follow.`,
658
+ },
659
+ 'coordination/spawn.md': {
660
+ title: 'Create Cognitive Patterns',
661
+ tool: 'mcp__ruv-swarm__agent_spawn',
662
+ params: '{"type": "researcher", "name": "Literature Analysis", "capabilities": ["deep-analysis"]}',
663
+ description: 'Define cognitive patterns that represent different approaches Claude Code can take',
664
+ details: `Agent types represent thinking patterns, not actual coders:
665
+ - **researcher**: Systematic exploration approach
666
+ - **coder**: Implementation-focused thinking
667
+ - **analyst**: Data-driven decision making
668
+ - **architect**: Big-picture system design
669
+ - **reviewer**: Quality and consistency checking
670
+
671
+ These patterns guide how Claude Code approaches different aspects of your task.`,
672
+ },
673
+ 'coordination/orchestrate.md': {
674
+ title: 'Coordinate Task Execution',
675
+ tool: 'mcp__ruv-swarm__task_orchestrate',
676
+ params: '{"task": "Implement authentication system", "strategy": "parallel", "priority": "high"}',
677
+ description: 'Break down and coordinate complex tasks for systematic execution by Claude Code',
678
+ details: `Orchestration strategies:
679
+ - **parallel**: Claude Code works on independent components simultaneously
680
+ - **sequential**: Step-by-step execution for dependent tasks
681
+ - **adaptive**: Dynamically adjusts based on task complexity
682
+
683
+ The orchestrator creates a plan that Claude Code follows using its native tools.`,
684
+ },
685
+
686
+ // Monitoring commands
687
+ 'monitoring/status.md': {
688
+ title: 'Check Coordination Status',
689
+ tool: 'mcp__ruv-swarm__swarm_status',
690
+ params: '{"verbose": true}',
691
+ description: 'Monitor the effectiveness of current coordination patterns',
692
+ details: `Shows:
693
+ - Active coordination topologies
694
+ - Current cognitive patterns in use
695
+ - Task breakdown and progress
696
+ - Resource utilization for coordination
697
+ - Overall system health`,
698
+ },
699
+ 'monitoring/agents.md': {
700
+ title: 'List Active Patterns',
701
+ tool: 'mcp__ruv-swarm__agent_list',
702
+ params: '{"filter": "active"}',
703
+ description: 'View all active cognitive patterns and their current focus areas',
704
+ details: `Filters:
705
+ - **all**: Show all defined patterns
706
+ - **active**: Currently engaged patterns
707
+ - **idle**: Available but unused patterns
708
+ - **busy**: Patterns actively coordinating tasks`,
709
+ },
710
+
711
+ // Memory commands
712
+ 'memory/usage.md': {
713
+ title: 'Memory Management',
714
+ tool: 'mcp__ruv-swarm__memory_usage',
715
+ params: '{"detail": "detailed"}',
716
+ description: 'Track persistent memory usage across Claude Code sessions',
717
+ details: `Memory helps Claude Code:
718
+ - Maintain context between sessions
719
+ - Remember project decisions
720
+ - Track implementation patterns
721
+ - Store coordination strategies that worked well`,
722
+ },
723
+ 'memory/neural.md': {
724
+ title: 'Neural Pattern Training',
725
+ tool: 'mcp__ruv-swarm__neural_train',
726
+ params: '{"iterations": 10}',
727
+ description: 'Improve coordination patterns through neural network training',
728
+ details: `Training improves:
729
+ - Task breakdown effectiveness
730
+ - Coordination pattern selection
731
+ - Resource allocation strategies
732
+ - Overall coordination efficiency`,
733
+ },
734
+
735
+ // Workflow examples
736
+ 'workflows/research.md': {
737
+ title: 'Research Workflow Coordination',
738
+ content: `# Research Workflow Coordination
739
+
740
+ ## Purpose
741
+ Coordinate Claude Code's research activities for comprehensive, systematic exploration.
742
+
743
+ ## Step-by-Step Coordination
744
+
745
+ ### 1. Initialize Research Framework
746
+ \`\`\`
747
+ Tool: mcp__ruv-swarm__swarm_init
748
+ Parameters: {"topology": "mesh", "maxAgents": 5, "strategy": "balanced"}
749
+ \`\`\`
750
+ Creates a mesh topology for comprehensive exploration from multiple angles.
751
+
752
+ ### 2. Define Research Perspectives
753
+ \`\`\`
754
+ Tool: mcp__ruv-swarm__agent_spawn
755
+ Parameters: {"type": "researcher", "name": "Literature Review"}
756
+ \`\`\`
757
+ \`\`\`
758
+ Tool: mcp__ruv-swarm__agent_spawn
759
+ Parameters: {"type": "analyst", "name": "Data Analysis"}
760
+ \`\`\`
761
+ Sets up different analytical approaches for Claude Code to use.
762
+
763
+ ### 3. Execute Coordinated Research
764
+ \`\`\`
765
+ Tool: mcp__ruv-swarm__task_orchestrate
766
+ Parameters: {"task": "Research modern web frameworks performance", "strategy": "adaptive"}
767
+ \`\`\`
768
+
769
+ ## What Claude Code Actually Does
770
+ 1. Uses **WebSearch** tool for finding resources
771
+ 2. Uses **Read** tool for analyzing documentation
772
+ 3. Uses **Task** tool for parallel exploration
773
+ 4. Synthesizes findings using coordination patterns
774
+ 5. Stores insights in memory for future reference
775
+
776
+ Remember: The swarm coordinates HOW Claude Code researches, not WHAT it finds.`,
777
+ },
778
+ 'workflows/development.md': {
779
+ title: 'Development Workflow Coordination',
780
+ content: `# Development Workflow Coordination
781
+
782
+ ## Purpose
783
+ Structure Claude Code's approach to complex development tasks for maximum efficiency.
784
+
785
+ ## Step-by-Step Coordination
786
+
787
+ ### 1. Initialize Development Framework
788
+ \`\`\`
789
+ Tool: mcp__ruv-swarm__swarm_init
790
+ Parameters: {"topology": "hierarchical", "maxAgents": 8, "strategy": "specialized"}
791
+ \`\`\`
792
+ Creates hierarchical structure for organized, top-down development.
793
+
794
+ ### 2. Define Development Perspectives
795
+ \`\`\`
796
+ Tool: mcp__ruv-swarm__agent_spawn
797
+ Parameters: {"type": "architect", "name": "System Design"}
798
+ \`\`\`
799
+ \`\`\`
800
+ Tool: mcp__ruv-swarm__agent_spawn
801
+ Parameters: {"type": "coder", "name": "Implementation Focus"}
802
+ \`\`\`
803
+ Sets up architectural and implementation thinking patterns.
804
+
805
+ ### 3. Coordinate Implementation
806
+ \`\`\`
807
+ Tool: mcp__ruv-swarm__task_orchestrate
808
+ Parameters: {"task": "Build REST API with authentication", "strategy": "parallel", "priority": "high"}
809
+ \`\`\`
810
+
811
+ ## What Claude Code Actually Does
812
+ 1. Uses **Write** tool to create new files
813
+ 2. Uses **Edit/MultiEdit** tools for code modifications
814
+ 3. Uses **Bash** tool for testing and building
815
+ 4. Uses **TodoWrite** tool for task tracking
816
+ 5. Follows coordination patterns for systematic implementation
817
+
818
+ Remember: All code is written by Claude Code using its native tools!`,
819
+ },
820
+
821
+ // Hook commands
822
+ 'hooks/overview.md': {
823
+ title: 'Claude Code Hooks Overview',
824
+ content: `# Claude Code Hooks for @sparkleideas/ruv-swarm
825
+
826
+ ## Purpose
827
+ Automatically coordinate, format, and learn from Claude Code operations using hooks.
828
+
829
+ ## Available Hooks
830
+
831
+ ### Pre-Operation Hooks
832
+ - **pre-edit**: Validate and assign agents before file modifications
833
+ - **pre-bash**: Check command safety and resource requirements
834
+ - **pre-task**: Auto-spawn agents for complex tasks
835
+
836
+ ### Post-Operation Hooks
837
+ - **post-edit**: Auto-format code and train neural patterns
838
+ - **post-bash**: Log execution and update metrics
839
+ - **post-search**: Cache results and improve search patterns
840
+
841
+ ### MCP Integration Hooks
842
+ - **mcp-initialized**: Persist swarm configuration
843
+ - **agent-spawned**: Update agent roster
844
+ - **task-orchestrated**: Monitor task progress
845
+ - **neural-trained**: Save pattern improvements
846
+
847
+ ### Session Hooks
848
+ - **notify**: Custom notifications with swarm status
849
+ - **session-end**: Generate summary and save state
850
+ - **session-restore**: Load previous session state
851
+
852
+ ## Configuration
853
+ Hooks are configured in \`.claude/settings.json\`:
854
+
855
+ \`\`\`json
856
+ {
857
+ "hooks": {
858
+ "PreToolUse": [
859
+ {
860
+ "matcher": "^(Write|Edit|MultiEdit)$",
861
+ "hooks": [{
862
+ "type": "command",
863
+ "command": "npx @sparkleideas/ruv-swarm hook pre-edit --file '\${tool.params.file_path}'"
864
+ }]
865
+ }
866
+ ]
867
+ }
868
+ }
869
+ \`\`\`
870
+
871
+ ## Benefits
872
+ - 🤖 Automatic agent assignment based on file type
873
+ - 🎨 Consistent code formatting
874
+ - 🧠 Continuous neural pattern improvement
875
+ - 💾 Cross-session memory persistence
876
+ - 📊 Performance metrics tracking
877
+
878
+ ## See Also
879
+ - [Pre-Edit Hook](./pre-edit.md)
880
+ - [Post-Edit Hook](./post-edit.md)
881
+ - [Session End Hook](./session-end.md)`,
882
+ },
883
+ 'hooks/setup.md': {
884
+ title: 'Setting Up Hooks',
885
+ content: `# Setting Up @sparkleideas/ruv-swarm Hooks
886
+
887
+ ## Quick Start
888
+
889
+ ### 1. Initialize with Hooks
890
+ \`\`\`bash
891
+ npx @sparkleideas/ruv-swarm init --claude --force
892
+ \`\`\`
893
+
894
+ This automatically creates:
895
+ - \`.claude/settings.json\` with hook configurations
896
+ - Hook command documentation
897
+ - Default hook handlers
898
+
899
+ ### 2. Test Hook Functionality
900
+ \`\`\`bash
901
+ # Test pre-edit hook
902
+ npx @sparkleideas/ruv-swarm hook pre-edit --file test.js --ensure-coordination
903
+
904
+ # Test session summary
905
+ npx @sparkleideas/ruv-swarm hook session-end --generate-summary
906
+ \`\`\`
907
+
908
+ ### 3. Customize Hooks
909
+
910
+ Edit \`.claude/settings.json\` to customize:
911
+
912
+ \`\`\`json
913
+ {
914
+ "hooks": {
915
+ "PreToolUse": [
916
+ {
917
+ "matcher": "^Write$",
918
+ "hooks": [{
919
+ "type": "command",
920
+ "command": "npx @sparkleideas/ruv-swarm hook custom-pre-write --file '\${tool.params.file_path}'"
921
+ }]
922
+ }
923
+ ]
924
+ }
925
+ }
926
+ \`\`\`
927
+
928
+ ## Hook Response Format
929
+
930
+ Hooks return JSON with:
931
+ - \`continue\`: Whether to proceed (true/false)
932
+ - \`reason\`: Explanation for decision
933
+ - \`metadata\`: Additional context
934
+
935
+ Example blocking response:
936
+ \`\`\`json
937
+ {
938
+ "continue": false,
939
+ "reason": "Protected file - manual review required",
940
+ "metadata": {
941
+ "file": ".env.production",
942
+ "protection_level": "high"
943
+ }
944
+ }
945
+ \`\`\`
946
+
947
+ ## Performance Tips
948
+ - Keep hooks lightweight (< 100ms)
949
+ - Use caching for repeated operations
950
+ - Batch related operations
951
+ - Run non-critical hooks asynchronously
952
+
953
+ ## Debugging Hooks
954
+ \`\`\`bash
955
+ # Enable debug output
956
+ export RUV_SWARM_HOOK_DEBUG=true
957
+
958
+ # Test specific hook
959
+ npx @sparkleideas/ruv-swarm hook pre-edit --file app.js --debug
960
+ \`\`\`
961
+
962
+ ## Common Patterns
963
+
964
+ ### Auto-Format on Save
965
+ Already configured by default for common file types.
966
+
967
+ ### Protected File Detection
968
+ \`\`\`json
969
+ {
970
+ "matcher": "^(Write|Edit)$",
971
+ "hooks": [{
972
+ "type": "command",
973
+ "command": "npx @sparkleideas/ruv-swarm hook check-protected --file '\${tool.params.file_path}'"
974
+ }]
975
+ }
976
+ \`\`\`
977
+
978
+ ### Automatic Testing
979
+ \`\`\`json
980
+ {
981
+ "matcher": "^Write$",
982
+ "hooks": [{
983
+ "type": "command",
984
+ "command": "test -f '\${tool.params.file_path%.js}.test.js' && npm test '\${tool.params.file_path%.js}.test.js'"
985
+ }]
986
+ }
987
+ \`\`\``,
988
+ },
989
+ };
990
+
991
+ const createdFiles = [];
992
+
993
+ // Generate command files
994
+ for (const [filepath, config] of Object.entries(commands)) {
995
+ let content;
996
+
997
+ if (config.content) {
998
+ // Use provided content for workflow files
999
+ ({ content } = config);
1000
+ } else {
1001
+ // Generate content for tool documentation
1002
+ content = `# ${config.title}
1003
+
1004
+ ## 🎯 Key Principle
1005
+ **This tool coordinates Claude Code's actions. It does NOT write code or create content.**
1006
+
1007
+ ## MCP Tool Usage in Claude Code
1008
+
1009
+ **Tool:** \`${config.tool}\`
1010
+
1011
+ ## Parameters
1012
+ \`\`\`json
1013
+ ${config.params}
1014
+ \`\`\`
1015
+
1016
+ ## Description
1017
+ ${config.description}
1018
+
1019
+ ## Details
1020
+ ${config.details}
1021
+
1022
+ ## Example Usage
1023
+
1024
+ **In Claude Code:**
1025
+ 1. Use the tool: \`${config.tool}\`
1026
+ 2. With parameters: \`${config.params}\`
1027
+ 3. Claude Code then executes the coordinated plan using its native tools
1028
+
1029
+ ## Important Reminders
1030
+ - ✅ This tool provides coordination and structure
1031
+ - ✅ Claude Code performs all actual implementation
1032
+ - ❌ The tool does NOT write code
1033
+ - ❌ The tool does NOT access files directly
1034
+ - ❌ The tool does NOT execute commands
1035
+
1036
+ ## See Also
1037
+ - Main documentation: /claude.md
1038
+ - Other commands in this category
1039
+ - Workflow examples in /workflows/
1040
+ `;
1041
+ }
1042
+
1043
+ const filePath = path.join(commandsDir, filepath);
1044
+ await fs.writeFile(filePath, content);
1045
+ createdFiles.push(filepath);
1046
+ }
1047
+
1048
+ return { files: createdFiles, success: true };
1049
+ }
1050
+
1051
+ /**
1052
+ * Generate settings.json with hook configurations
1053
+ */
1054
+ async generateSettingsJson() {
1055
+ const settings = {
1056
+ env: {
1057
+ RUV_SWARM_AUTO_COMMIT: 'false',
1058
+ RUV_SWARM_AUTO_PUSH: 'false',
1059
+ RUV_SWARM_HOOKS_ENABLED: 'false',
1060
+ RUV_SWARM_TELEMETRY_ENABLED: 'true',
1061
+ RUV_SWARM_REMOTE_EXECUTION: 'true',
1062
+ },
1063
+ permissions: {
1064
+ allow: [
1065
+ 'Bash(npx @sparkleideas/ruv-swarm *)',
1066
+ 'Bash(npm run lint)',
1067
+ 'Bash(npm run test:*)',
1068
+ 'Bash(npm test *)',
1069
+ 'Bash(git status)',
1070
+ 'Bash(git diff *)',
1071
+ 'Bash(git log *)',
1072
+ 'Bash(git add *)',
1073
+ 'Bash(git commit *)',
1074
+ 'Bash(git push)',
1075
+ 'Bash(git config *)',
1076
+ 'Bash(node *)',
1077
+ 'Bash(which *)',
1078
+ 'Bash(pwd)',
1079
+ 'Bash(ls *)',
1080
+ ],
1081
+ deny: [
1082
+ 'Bash(rm -rf /)',
1083
+ 'Bash(curl * | bash)',
1084
+ 'Bash(wget * | sh)',
1085
+ 'Bash(eval *)',
1086
+ ],
1087
+ },
1088
+ hooks: {},
1089
+ mcpServers: {
1090
+ '@sparkleideas/ruv-swarm': {
1091
+ command: 'npx',
1092
+ args: ['@sparkleideas/ruv-swarm', 'mcp', 'start'],
1093
+ env: {
1094
+ RUV_SWARM_HOOKS_ENABLED: 'false',
1095
+ RUV_SWARM_TELEMETRY_ENABLED: 'true',
1096
+ RUV_SWARM_REMOTE_READY: 'true',
1097
+ },
1098
+ },
1099
+ },
1100
+ includeCoAuthoredBy: true,
1101
+ };
1102
+
1103
+ const filePath = path.join(this.workingDir, '.claude', 'settings.json');
1104
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
1105
+ await fs.writeFile(filePath, JSON.stringify(settings, null, 2));
1106
+
1107
+ return { file: '.claude/settings.json', success: true };
1108
+ }
1109
+
1110
+ /**
1111
+ * Check if file exists
1112
+ */
1113
+ async fileExists(filePath) {
1114
+ try {
1115
+ await fs.access(filePath);
1116
+ return true;
1117
+ } catch {
1118
+ return false;
1119
+ }
1120
+ }
1121
+
1122
+ /**
1123
+ * Create backup of existing file
1124
+ */
1125
+ async createBackup(filePath) {
1126
+ const timestamp = new Date().toISOString().slice(0, 19).replace(/[:-]/g, '');
1127
+ const backupPath = `${filePath}.backup.${timestamp}`;
1128
+
1129
+ try {
1130
+ await fs.copyFile(filePath, backupPath);
1131
+ console.log(`📄 Backup created: ${path.basename(backupPath)}`);
1132
+ return backupPath;
1133
+ } catch (error) {
1134
+ console.error('⚠️ Failed to create backup:', error.message);
1135
+ throw error;
1136
+ }
1137
+ }
1138
+
1139
+ /**
1140
+ * Clean up old backup files (keep last 5)
1141
+ */
1142
+ async cleanupOldBackups(filePath) {
1143
+ const dir = path.dirname(filePath);
1144
+ const baseName = path.basename(filePath);
1145
+
1146
+ try {
1147
+ const files = await fs.readdir(dir);
1148
+ const backupFiles = files
1149
+ .filter(file => file.startsWith(`${baseName}.backup.`))
1150
+ .sort()
1151
+ .reverse(); // Most recent first
1152
+
1153
+ // Keep only the 5 most recent backups
1154
+ const filesToDelete = backupFiles.slice(5);
1155
+
1156
+ for (const file of filesToDelete) {
1157
+ try {
1158
+ await fs.unlink(path.join(dir, file));
1159
+ } catch {
1160
+ // Ignore errors deleting old backups
1161
+ }
1162
+ }
1163
+ } catch {
1164
+ // Ignore errors in cleanup
1165
+ }
1166
+ }
1167
+
1168
+ /**
1169
+ * Prompt user for action when CLAUDE.md exists
1170
+ */
1171
+ async promptUserAction(filePath) {
1172
+ // In a CLI environment, we need to use a different approach
1173
+ // For now, we'll use process.stdin/stdout directly
1174
+ const readline = await import('readline');
1175
+
1176
+ const rl = readline.createInterface({
1177
+ input: process.stdin,
1178
+ output: process.stdout,
1179
+ });
1180
+
1181
+ return new Promise((resolve) => {
1182
+ console.log(`\n📁 CLAUDE.md already exists at: ${filePath}`);
1183
+ console.log('Choose an action:');
1184
+ console.log(' [o] Overwrite (creates backup)');
1185
+ console.log(' [m] Merge with existing content');
1186
+ console.log(' [c] Cancel operation');
1187
+
1188
+ rl.question('\nYour choice (o/m/c): ', (answer) => {
1189
+ rl.close();
1190
+
1191
+ switch (answer.toLowerCase()) {
1192
+ case 'o':
1193
+ case 'overwrite':
1194
+ resolve('overwrite');
1195
+ break;
1196
+ case 'm':
1197
+ case 'merge':
1198
+ resolve('merge');
1199
+ break;
1200
+ case 'c':
1201
+ case 'cancel':
1202
+ default:
1203
+ resolve('cancel');
1204
+ }
1205
+ });
1206
+ });
1207
+ }
1208
+
1209
+ /**
1210
+ * Merge @sparkleideas/ruv-swarm content with existing CLAUDE.md
1211
+ */
1212
+ async mergeClaudeMd(filePath, noBackup = false) {
1213
+ try {
1214
+ const existingContent = await fs.readFile(filePath, 'utf8');
1215
+
1216
+ console.log('📝 Merging @sparkleideas/ruv-swarm configuration with existing CLAUDE.md');
1217
+
1218
+ // Create backup first (unless disabled)
1219
+ if (!noBackup) {
1220
+ await this.createBackup(filePath);
1221
+ } else {
1222
+ console.log('📝 Skipping backup creation (disabled by --no-backup)');
1223
+ }
1224
+
1225
+ // Generate new @sparkleideas/ruv-swarm content
1226
+ const ruvSwarmContent = this.getRuvSwarmContent();
1227
+
1228
+ // Intelligent merging
1229
+ const mergedContent = this.intelligentMerge(existingContent, ruvSwarmContent);
1230
+
1231
+ // Write merged content
1232
+ await fs.writeFile(filePath, mergedContent);
1233
+
1234
+ console.log('✅ Successfully merged @sparkleideas/ruv-swarm configuration with existing CLAUDE.md');
1235
+
1236
+ return { file: 'CLAUDE.md', success: true, action: 'merged' };
1237
+ } catch (error) {
1238
+ console.error('❌ Failed to merge CLAUDE.md:', error.message);
1239
+ throw error;
1240
+ }
1241
+ }
1242
+
1243
+ /**
1244
+ * Get the @sparkleideas/ruv-swarm specific content (full content from generateClaudeMd)
1245
+ */
1246
+ getRuvSwarmContent() {
1247
+ // Return the complete @sparkleideas/ruv-swarm configuration content
1248
+ const content = `# Claude Code Configuration for @sparkleideas/ruv-swarm
1249
+
1250
+ ## 🎯 IMPORTANT: Separation of Responsibilities
1251
+
1252
+ ### Claude Code Handles:
1253
+ - ✅ **ALL file operations** (Read, Write, Edit, MultiEdit)
1254
+ - ✅ **ALL code generation** and development tasks
1255
+ - ✅ **ALL bash commands** and system operations
1256
+ - ✅ **ALL actual implementation** work
1257
+ - ✅ **Project navigation** and code analysis
1258
+
1259
+ ### @sparkleideas/ruv-swarm MCP Tools Handle:
1260
+ - 🧠 **Coordination only** - Orchestrating Claude Code's actions
1261
+ - 💾 **Memory management** - Persistent state across sessions
1262
+ - 🤖 **Neural features** - Cognitive patterns and learning
1263
+ - 📊 **Performance tracking** - Monitoring and metrics
1264
+ - 🐝 **Swarm orchestration** - Multi-agent coordination
1265
+
1266
+ ### ⚠️ Key Principle:
1267
+ **MCP tools DO NOT create content or write code.** They coordinate and enhance Claude Code's native capabilities. Think of them as an orchestration layer that helps Claude Code work more efficiently.
1268
+
1269
+ ## 🚀 CRITICAL: Parallel Execution & Batch Operations
1270
+
1271
+ ### 🚨 MANDATORY RULE #1: BATCH EVERYTHING
1272
+
1273
+ **When using swarms, you MUST use BatchTool for ALL operations:**
1274
+
1275
+ 1. **NEVER** send multiple messages for related operations
1276
+ 2. **ALWAYS** combine multiple tool calls in ONE message
1277
+ 3. **PARALLEL** execution is MANDATORY, not optional
1278
+
1279
+ ### ⚡ THE GOLDEN RULE OF SWARMS
1280
+
1281
+ \`\`\`
1282
+ If you need to do X operations, they should be in 1 message, not X messages
1283
+ \`\`\`
1284
+
1285
+ ### 📦 BATCH TOOL EXAMPLES
1286
+
1287
+ **✅ CORRECT - Everything in ONE Message:**
1288
+ \`\`\`javascript
1289
+ [Single Message with BatchTool]:
1290
+ mcp__ruv-swarm__swarm_init { topology: "mesh", maxAgents: 6 }
1291
+ mcp__ruv-swarm__agent_spawn { type: "researcher" }
1292
+ mcp__ruv-swarm__agent_spawn { type: "coder" }
1293
+ mcp__ruv-swarm__agent_spawn { type: "analyst" }
1294
+ mcp__ruv-swarm__agent_spawn { type: "tester" }
1295
+ mcp__ruv-swarm__agent_spawn { type: "coordinator" }
1296
+ TodoWrite { todos: [todo1, todo2, todo3, todo4, todo5] }
1297
+ Bash "mkdir -p app/{src,tests,docs}"
1298
+ Write "app/package.json"
1299
+ Write "app/README.md"
1300
+ Write "app/src/index.js"
1301
+ \`\`\`
1302
+
1303
+ **❌ WRONG - Multiple Messages (NEVER DO THIS):**
1304
+ \`\`\`javascript
1305
+ Message 1: mcp__ruv-swarm__swarm_init
1306
+ Message 2: mcp__ruv-swarm__agent_spawn
1307
+ Message 3: mcp__ruv-swarm__agent_spawn
1308
+ Message 4: TodoWrite (one todo)
1309
+ Message 5: Bash "mkdir src"
1310
+ Message 6: Write "package.json"
1311
+ // This is 6x slower and breaks parallel coordination!
1312
+ \`\`\`
1313
+
1314
+ ### 🎯 BATCH OPERATIONS BY TYPE
1315
+
1316
+ **File Operations (Single Message):**
1317
+ - Read 10 files? → One message with 10 Read calls
1318
+ - Write 5 files? → One message with 5 Write calls
1319
+ - Edit 1 file many times? → One MultiEdit call
1320
+
1321
+ **Swarm Operations (Single Message):**
1322
+ - Need 8 agents? → One message with swarm_init + 8 agent_spawn calls
1323
+ - Multiple memories? → One message with all memory_usage calls
1324
+ - Task + monitoring? → One message with task_orchestrate + swarm_monitor
1325
+
1326
+ **Command Operations (Single Message):**
1327
+ - Multiple directories? → One message with all mkdir commands
1328
+ - Install + test + lint? → One message with all npm commands
1329
+ - Git operations? → One message with all git commands
1330
+
1331
+ ## 🚀 Quick Setup (Stdio MCP - Recommended)
1332
+
1333
+ ### 1. Add MCP Server (Stdio - No Port Needed)
1334
+ \`\`\`bash
1335
+ # Add @sparkleideas/ruv-swarm MCP server to Claude Code using stdio
1336
+ claude mcp add @sparkleideas/ruv-swarm npx @sparkleideas/ruv-swarm mcp start
1337
+ \`\`\`
1338
+
1339
+ ### 2. Use MCP Tools for Coordination in Claude Code
1340
+ Once configured, @sparkleideas/ruv-swarm MCP tools enhance Claude Code's coordination:
1341
+
1342
+ **Initialize a swarm:**
1343
+ - Use the \`mcp__ruv-swarm__swarm_init\` tool to set up coordination topology
1344
+ - Choose: mesh, hierarchical, ring, or star
1345
+ - This creates a coordination framework for Claude Code's work
1346
+
1347
+ **Spawn agents:**
1348
+ - Use \`mcp__ruv-swarm__agent_spawn\` tool to create specialized coordinators
1349
+ - Agent types represent different thinking patterns, not actual coders
1350
+ - They help Claude Code approach problems from different angles
1351
+
1352
+ **Orchestrate tasks:**
1353
+ - Use \`mcp__ruv-swarm__task_orchestrate\` tool to coordinate complex workflows
1354
+ - This breaks down tasks for Claude Code to execute systematically
1355
+ - The agents don't write code - they coordinate Claude Code's actions
1356
+
1357
+ ## Available MCP Tools for Coordination
1358
+
1359
+ ### Coordination Tools:
1360
+ - \`mcp__ruv-swarm__swarm_init\` - Set up coordination topology for Claude Code
1361
+ - \`mcp__ruv-swarm__agent_spawn\` - Create cognitive patterns to guide Claude Code
1362
+ - \`mcp__ruv-swarm__task_orchestrate\` - Break down and coordinate complex tasks
1363
+
1364
+ ### Monitoring Tools:
1365
+ - \`mcp__ruv-swarm__swarm_status\` - Monitor coordination effectiveness
1366
+ - \`mcp__ruv-swarm__agent_list\` - View active cognitive patterns
1367
+ - \`mcp__ruv-swarm__agent_metrics\` - Track coordination performance
1368
+ - \`mcp__ruv-swarm__task_status\` - Check workflow progress
1369
+ - \`mcp__ruv-swarm__task_results\` - Review coordination outcomes
1370
+
1371
+ ### Memory & Neural Tools:
1372
+ - \`mcp__ruv-swarm__memory_usage\` - Persistent memory across sessions
1373
+ - \`mcp__ruv-swarm__neural_status\` - Neural pattern effectiveness
1374
+ - \`mcp__ruv-swarm__neural_train\` - Improve coordination patterns
1375
+ - \`mcp__ruv-swarm__neural_patterns\` - Analyze thinking approaches
1376
+
1377
+ ### System Tools:
1378
+ - \`mcp__ruv-swarm__benchmark_run\` - Measure coordination efficiency
1379
+ - \`mcp__ruv-swarm__features_detect\` - Available capabilities
1380
+ - \`mcp__ruv-swarm__swarm_monitor\` - Real-time coordination tracking
1381
+
1382
+ ## Best Practices for Coordination
1383
+
1384
+ ### ✅ DO:
1385
+ - Use MCP tools to coordinate Claude Code's approach to complex tasks
1386
+ - Let the swarm break down problems into manageable pieces
1387
+ - Use memory tools to maintain context across sessions
1388
+ - Monitor coordination effectiveness with status tools
1389
+ - Train neural patterns for better coordination over time
1390
+
1391
+ ### ❌ DON'T:
1392
+ - Expect agents to write code (Claude Code does all implementation)
1393
+ - Use MCP tools for file operations (use Claude Code's native tools)
1394
+ - Try to make agents execute bash commands (Claude Code handles this)
1395
+ - Confuse coordination with execution (MCP coordinates, Claude executes)
1396
+
1397
+ ## Performance Benefits
1398
+
1399
+ When using @sparkleideas/ruv-swarm coordination with Claude Code:
1400
+ - **84.8% SWE-Bench solve rate** - Better problem-solving through coordination
1401
+ - **32.3% token reduction** - Efficient task breakdown reduces redundancy
1402
+ - **2.8-4.4x speed improvement** - Parallel coordination strategies
1403
+ - **27+ neural models** - Diverse cognitive approaches
1404
+
1405
+ ## Support
1406
+
1407
+ - Documentation: https://github.com/ruvnet/ruv-FANN/tree/main/ruv-swarm
1408
+ - Issues: https://github.com/ruvnet/ruv-FANN/issues
1409
+ - Examples: https://github.com/ruvnet/ruv-FANN/tree/main/ruv-swarm/examples
1410
+
1411
+ ---
1412
+
1413
+ Remember: **@sparkleideas/ruv-swarm coordinates, Claude Code creates!** Start with \`mcp__ruv-swarm__swarm_init\` to enhance your development workflow.`;
1414
+
1415
+ return content;
1416
+ }
1417
+
1418
+ /**
1419
+ * Intelligently combine @sparkleideas/ruv-swarm content with existing content
1420
+ */
1421
+ intelligentMerge(existingContent, ruvSwarmContent) {
1422
+ const existingLines = existingContent.split('\n');
1423
+ const newLines = ruvSwarmContent.split('\n');
1424
+
1425
+ // Check if @sparkleideas/ruv-swarm content already exists
1426
+ const ruvSwarmSectionIndex = this.findRuvSwarmSection(existingLines);
1427
+
1428
+ if (ruvSwarmSectionIndex !== -1) {
1429
+ // Replace existing @sparkleideas/ruv-swarm section
1430
+ console.log('📝 Updating existing @sparkleideas/ruv-swarm section in CLAUDE.md');
1431
+ const sectionEnd = this.findSectionEnd(existingLines, ruvSwarmSectionIndex);
1432
+
1433
+ // Replace the section
1434
+ const beforeSection = existingLines.slice(0, ruvSwarmSectionIndex);
1435
+ const afterSection = existingLines.slice(sectionEnd);
1436
+
1437
+ return [...beforeSection, ...newLines, '', ...afterSection].join('\n');
1438
+ }
1439
+ // Intelligently insert @sparkleideas/ruv-swarm content
1440
+ console.log('📝 Integrating @sparkleideas/ruv-swarm configuration into existing CLAUDE.md');
1441
+ return this.intelligentInsert(existingLines, newLines);
1442
+
1443
+ }
1444
+
1445
+ /**
1446
+ * Find existing @sparkleideas/ruv-swarm section in content
1447
+ */
1448
+ findRuvSwarmSection(lines) {
1449
+ for (let i = 0; i < lines.length; i++) {
1450
+ const line = lines[i].toLowerCase();
1451
+ if (line.includes('@sparkleideas/ruv-swarm') && (line.startsWith('#') || line.includes('claude code configuration'))) {
1452
+ return i;
1453
+ }
1454
+ }
1455
+ return -1;
1456
+ }
1457
+
1458
+ /**
1459
+ * Intelligently insert new content based on context
1460
+ */
1461
+ intelligentInsert(existingLines, newLines) {
1462
+ // Look for appropriate insertion points
1463
+ let insertIndex = -1;
1464
+
1465
+ // 1. After main title but before first major section
1466
+ for (let i = 0; i < existingLines.length; i++) {
1467
+ if (existingLines[i].startsWith('# ') && i > 0) {
1468
+ // Found first major heading after title
1469
+ insertIndex = i;
1470
+ break;
1471
+ }
1472
+ }
1473
+
1474
+ // 2. If no major headings, look for end of introductory content
1475
+ if (insertIndex === -1) {
1476
+ for (let i = 0; i < existingLines.length; i++) {
1477
+ if (existingLines[i].startsWith('## ') && i > 5) {
1478
+ insertIndex = i;
1479
+ break;
1480
+ }
1481
+ }
1482
+ }
1483
+
1484
+ // 3. Fallback: insert after first 10 lines or middle of file
1485
+ if (insertIndex === -1) {
1486
+ insertIndex = Math.min(10, Math.floor(existingLines.length / 2));
1487
+ }
1488
+
1489
+ // Insert the content with proper spacing
1490
+ const beforeInsert = existingLines.slice(0, insertIndex);
1491
+ const afterInsert = existingLines.slice(insertIndex);
1492
+
1493
+ // Add spacing
1494
+ const insertContent = ['', '---', '', ...newLines, '', '---', ''];
1495
+
1496
+ return [...beforeInsert, ...insertContent, ...afterInsert].join('\n');
1497
+ }
1498
+
1499
+ /**
1500
+ * Find the end of a markdown section
1501
+ */
1502
+ findSectionEnd(lines, startIndex) {
1503
+ // Look for next top-level heading or end of file
1504
+ for (let i = startIndex + 1; i < lines.length; i++) {
1505
+ if (lines[i].startsWith('# ') && !lines[i].includes('@sparkleideas/ruv-swarm')) {
1506
+ return i;
1507
+ }
1508
+ // Also check for horizontal rules that might separate sections
1509
+ if (lines[i].trim() === '---' && i > startIndex + 10) {
1510
+ return i;
1511
+ }
1512
+ }
1513
+ return lines.length;
1514
+ }
1515
+
1516
+ /**
1517
+ * Generate all documentation files
1518
+ */
1519
+ async generateAll(options = {}) {
1520
+ console.log('📚 Generating Claude Code documentation...');
1521
+
1522
+ try {
1523
+ const results = {
1524
+ claudeMd: await this.generateClaudeMd(options),
1525
+ commands: await this.generateCommandDocs(),
1526
+ advancedCommands: await this.advancedGenerator.generateAdvancedCommands(),
1527
+ settings: await this.generateSettingsJson(),
1528
+ success: true,
1529
+ };
1530
+
1531
+ const totalCommands = results.commands.files.length + results.advancedCommands.files.length;
1532
+
1533
+ console.log('✅ Documentation generated successfully');
1534
+ console.log(' - CLAUDE.md');
1535
+ console.log(' - .claude/settings.json (with enhanced hooks)');
1536
+ console.log(` - .claude/commands/ directory with ${ totalCommands } files`);
1537
+ console.log(` • Basic commands: ${ results.commands.files.length}`);
1538
+ console.log(` • Advanced optimization: ${ results.advancedCommands.files.length}`);
1539
+
1540
+ return results;
1541
+ } catch (error) {
1542
+ console.error('❌ Failed to generate documentation:', error.message);
1543
+ throw error;
1544
+ }
1545
+ }
1546
+ }
1547
+
1548
+ export { ClaudeDocsGenerator };