claude-mycelium 2.1.0 → 2.2.0

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 (39) hide show
  1. package/.agent-meta/tasks/_active.json +4 -0
  2. package/.agent-meta/tasks/task_0657b028-05a0-4b0c-b0b9-a4eae3d66cd9.json +168 -0
  3. package/README.md +6 -0
  4. package/dist/agent/task-worker.d.ts +11 -0
  5. package/dist/agent/task-worker.d.ts.map +1 -0
  6. package/dist/agent/task-worker.js +173 -0
  7. package/dist/agent/task-worker.js.map +1 -0
  8. package/dist/cli/gradients.d.ts.map +1 -1
  9. package/dist/cli/gradients.js +1 -0
  10. package/dist/cli/gradients.js.map +1 -1
  11. package/dist/cli/grow.d.ts +17 -0
  12. package/dist/cli/grow.d.ts.map +1 -0
  13. package/dist/cli/grow.js +373 -0
  14. package/dist/cli/grow.js.map +1 -0
  15. package/dist/cli/index.d.ts.map +1 -1
  16. package/dist/cli/index.js +2 -0
  17. package/dist/cli/index.js.map +1 -1
  18. package/dist/core/agent-executor.d.ts +4 -1
  19. package/dist/core/agent-executor.d.ts.map +1 -1
  20. package/dist/core/agent-executor.js +10 -2
  21. package/dist/core/agent-executor.js.map +1 -1
  22. package/dist/task/agent-coordinator.d.ts +40 -0
  23. package/dist/task/agent-coordinator.d.ts.map +1 -0
  24. package/dist/task/agent-coordinator.js +168 -0
  25. package/dist/task/agent-coordinator.js.map +1 -0
  26. package/dist/task/executor.d.ts +9 -2
  27. package/dist/task/executor.d.ts.map +1 -1
  28. package/dist/task/executor.js +64 -31
  29. package/dist/task/executor.js.map +1 -1
  30. package/docs/ROADMAP.md +139 -59
  31. package/package.json +10 -2
  32. package/src/agent/task-worker.ts +196 -0
  33. package/src/cli/gradients.ts +2 -0
  34. package/src/cli/grow.ts +416 -0
  35. package/src/cli/index.ts +2 -0
  36. package/src/core/agent-executor.ts +17 -4
  37. package/src/task/agent-coordinator.ts +220 -0
  38. package/src/task/executor.ts +71 -66
  39. package/tests/trace/trace-event.test.ts +62 -20
@@ -0,0 +1,416 @@
1
+ /**
2
+ * Grow CLI Command - Interactive Mycelium Growth Interface
3
+ *
4
+ * Interactive terminal for spawning agents to improve your codebase
5
+ * Usage: npx claude-mycelium grow
6
+ */
7
+
8
+ import { Command } from 'commander';
9
+ import prompts from 'prompts';
10
+ import chalk from 'chalk';
11
+ import ora from 'ora';
12
+ import { executeAgent } from '../core/agent-executor.js';
13
+ import { calculateGradient } from '../core/gradient.js';
14
+ import { planTask, executeTask } from '../task/index.js';
15
+ import { storeTask } from '../task/storage.js';
16
+ import type { Mode, Task } from '../types/index.js';
17
+ import { randomUUID } from 'crypto';
18
+
19
+ interface ParsedTask {
20
+ type: 'spawn' | 'analyze' | 'task' | 'help' | 'exit';
21
+ mode?: Mode;
22
+ file?: string;
23
+ description?: string;
24
+ }
25
+
26
+ /**
27
+ * Parse natural language task into action
28
+ */
29
+ function parseTask(input: string): ParsedTask {
30
+ const lower = input.toLowerCase().trim();
31
+
32
+ if (lower === 'help' || lower === '?') {
33
+ return { type: 'help' };
34
+ }
35
+
36
+ if (lower === 'exit' || lower === 'quit' || lower === 'q') {
37
+ return { type: 'exit' };
38
+ }
39
+
40
+ if (lower.startsWith('analyze ') || lower.startsWith('check ')) {
41
+ const file = lower.split(/\s+/).slice(1).join(' ');
42
+ return { type: 'analyze', file };
43
+ }
44
+
45
+ // Check if input has a file path - if so, use quick spawn commands
46
+ const file = extractFilePath(input);
47
+
48
+ if (file) {
49
+ // File-specific quick commands
50
+ if (lower.includes('fix') || lower.includes('bug') || lower.includes('error')) {
51
+ return { type: 'spawn', mode: 'error_reducer', file };
52
+ }
53
+
54
+ if (lower.includes('complex') || lower.includes('simplify') || lower.includes('reduce')) {
55
+ return { type: 'spawn', mode: 'complexity_reducer', file };
56
+ }
57
+
58
+ if (lower.includes('clean') || lower.includes('debt') || lower.includes('lint')) {
59
+ return { type: 'spawn', mode: 'debt_payer', file };
60
+ }
61
+
62
+ if (lower.includes('stabil') || lower.includes('churn')) {
63
+ return { type: 'spawn', mode: 'stabilizer', file };
64
+ }
65
+
66
+ // Has file but no recognized keywords - analyze it
67
+ return { type: 'analyze', file };
68
+ }
69
+
70
+ // No file path - treat as general task (like "implement MCP", "add health check", etc.)
71
+ // Keywords that indicate a general task
72
+ if (lower.includes('implement') ||
73
+ lower.includes('create') ||
74
+ lower.includes('add') ||
75
+ lower.includes('build') ||
76
+ lower.includes('make') ||
77
+ lower.includes('develop') ||
78
+ lower.includes('write') ||
79
+ lower.startsWith('let\'s')) {
80
+ return { type: 'task', description: input };
81
+ }
82
+
83
+ return { type: 'help' };
84
+ }
85
+
86
+ /**
87
+ * Extract file path from natural language
88
+ */
89
+ function extractFilePath(input: string): string | undefined {
90
+ const words = input.split(/\s+/);
91
+ const fileWord = words.find(
92
+ (w) => w.includes('/') || w.endsWith('.ts') || w.endsWith('.js') || w.endsWith('.tsx') || w.endsWith('.jsx')
93
+ );
94
+ return fileWord;
95
+ }
96
+
97
+ /**
98
+ * Show help message
99
+ */
100
+ function showHelp() {
101
+ console.log('');
102
+ console.log(chalk.bold.green('🍄 Claude Mycelium - Interactive Growth'));
103
+ console.log('');
104
+ console.log(chalk.bold('General Tasks (Multi-Step):'));
105
+ console.log('');
106
+ console.log(chalk.cyan(' "implement MCP server"') + ' - Plan and execute multi-step task');
107
+ console.log(chalk.cyan(' "add health check endpoint"') + ' - Create feature with tests');
108
+ console.log(chalk.cyan(' "create authentication system"') + ' - Build complete feature');
109
+ console.log('');
110
+ console.log(chalk.bold('File-Specific Commands (Quick):'));
111
+ console.log('');
112
+ console.log(chalk.cyan(' "fix bugs in src/api.ts"') + ' - Spawn error_reducer agent');
113
+ console.log(chalk.cyan(' "reduce complexity in src/utils.ts"') + ' - Spawn complexity_reducer agent');
114
+ console.log(chalk.cyan(' "clean up src/legacy.ts"') + ' - Spawn debt_payer agent');
115
+ console.log(chalk.cyan(' "stabilize src/volatile.ts"') + ' - Spawn stabilizer agent');
116
+ console.log(chalk.cyan(' "analyze src/app.ts"') + ' - Show gradient analysis');
117
+ console.log('');
118
+ console.log(chalk.dim(' Type "exit" to quit'));
119
+ console.log('');
120
+ }
121
+
122
+ /**
123
+ * Start interactive grow session
124
+ */
125
+ export async function startGrowSession() {
126
+ console.clear();
127
+ console.log(chalk.bold.green('🍄 Mycelium Network Active'));
128
+ console.log(chalk.dim('Growing intelligence through autonomous agents'));
129
+ console.log('');
130
+
131
+ showHelp();
132
+
133
+ let running = true;
134
+
135
+ while (running) {
136
+ try {
137
+ const response = await prompts({
138
+ type: 'text',
139
+ name: 'task',
140
+ message: chalk.green('🌱 What would you like to grow?'),
141
+ validate: (value) => value.length > 0 || 'Please enter a task',
142
+ });
143
+
144
+ if (!response.task) {
145
+ // User cancelled with Ctrl+C
146
+ running = false;
147
+ break;
148
+ }
149
+
150
+ const task = parseTask(response.task);
151
+
152
+ if (task.type === 'help') {
153
+ showHelp();
154
+ continue;
155
+ }
156
+
157
+ if (task.type === 'exit') {
158
+ running = false;
159
+ break;
160
+ }
161
+
162
+ if (task.type === 'analyze') {
163
+ if (!task.file) {
164
+ console.log(chalk.yellow('⚠️ Please specify a file to analyze'));
165
+ continue;
166
+ }
167
+
168
+ const spinner = ora(`Analyzing ${task.file}...`).start();
169
+ try {
170
+ const gradient = await calculateGradient(task.file);
171
+ spinner.succeed(chalk.green(`Analysis complete for ${task.file}`));
172
+
173
+ console.log('');
174
+ console.log(chalk.bold('📊 Gradient Analysis:'));
175
+ console.log(chalk.dim('─'.repeat(50)));
176
+ console.log(`${chalk.bold('Overall Score:')} ${gradient.score.toFixed(3)}`);
177
+ console.log(`${chalk.bold('Dominant Signal:')} ${gradient.dominantSignal.name}`);
178
+ console.log('');
179
+ console.log(chalk.dim('Signal Breakdown:'));
180
+ console.log(` Complexity: ${gradient.signals.complexity.toFixed(3)}`);
181
+ console.log(` Churn: ${gradient.signals.churn.toFixed(3)}`);
182
+ console.log(` Debt: ${gradient.signals.debt.toFixed(3)}`);
183
+ console.log(` Error Rate: ${gradient.signals.error_rate.toFixed(3)}`);
184
+ console.log(` Centrality: ${gradient.signals.centrality.toFixed(3)}`);
185
+ console.log('');
186
+ } catch (error) {
187
+ spinner.fail(chalk.red('Analysis failed'));
188
+ console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));
189
+ }
190
+ continue;
191
+ }
192
+
193
+ if (task.type === 'task') {
194
+ if (!task.description) {
195
+ console.log(chalk.yellow('⚠️ Could not determine task description'));
196
+ continue;
197
+ }
198
+
199
+ const spinner = ora('Planning task...').start();
200
+ try {
201
+ // Create task object
202
+ const newTask: Task = {
203
+ id: randomUUID(),
204
+ description: task.description,
205
+ status: 'planning',
206
+ created_at: new Date().toISOString(),
207
+ acceptance_criteria: [],
208
+ steps_completed: 0,
209
+ steps_total: 0,
210
+ files_created: [],
211
+ files_modified: [],
212
+ traces: [],
213
+ };
214
+
215
+ spinner.text = 'Generating task plan...';
216
+ const plan = await planTask(newTask);
217
+
218
+ newTask.plan = plan;
219
+ newTask.steps_total = plan.steps.length;
220
+ newTask.status = 'in_progress';
221
+
222
+ await storeTask(newTask);
223
+
224
+ spinner.succeed(chalk.green('Task plan generated'));
225
+ console.log('');
226
+ console.log(chalk.bold('📋 Task Plan:'));
227
+ console.log(chalk.dim('─'.repeat(50)));
228
+ console.log(`${chalk.bold('Summary:')} ${plan.summary}`);
229
+ console.log(`${chalk.bold('Steps:')} ${plan.steps.length}`);
230
+ console.log(`${chalk.bold('Complexity:')} ${plan.estimated_complexity}`);
231
+ if (plan.risks.length > 0) {
232
+ console.log(`${chalk.bold('Risks:')}`);
233
+ plan.risks.forEach(risk => console.log(chalk.yellow(` ⚠️ ${risk}`)));
234
+ }
235
+ console.log('');
236
+
237
+ // Show steps
238
+ console.log(chalk.bold('Steps:'));
239
+ plan.steps.forEach(step => {
240
+ console.log(` ${step.order}. ${step.description}`);
241
+ console.log(` ${chalk.dim(`File: ${step.target_file}, Mode: ${step.mode}`)}`);
242
+ });
243
+ console.log('');
244
+
245
+ const executeSpinner = ora('Executing task...').start();
246
+ const executedTask = await executeTask(newTask);
247
+
248
+ if (executedTask.status === 'completed') {
249
+ executeSpinner.succeed(chalk.green('Task completed successfully'));
250
+ console.log('');
251
+ console.log(chalk.bold('✅ Results:'));
252
+ console.log(chalk.dim('─'.repeat(50)));
253
+ console.log(`${chalk.bold('Task ID:')} ${executedTask.id}`);
254
+ console.log(`${chalk.bold('Steps:')} ${executedTask.steps_completed}/${executedTask.steps_total}`);
255
+ console.log(`${chalk.bold('Files Created:')} ${executedTask.files_created.length}`);
256
+ console.log(`${chalk.bold('Files Modified:')} ${executedTask.files_modified.length}`);
257
+ console.log('');
258
+
259
+ if (executedTask.files_created.length > 0) {
260
+ console.log(chalk.bold('Created:'));
261
+ executedTask.files_created.forEach(f => console.log(` ${chalk.green('+')} ${f}`));
262
+ }
263
+ if (executedTask.files_modified.length > 0) {
264
+ console.log(chalk.bold('Modified:'));
265
+ executedTask.files_modified.forEach(f => console.log(` ${chalk.yellow('~')} ${f}`));
266
+ }
267
+ console.log('');
268
+ console.log(chalk.green('💡 Task completed. Run tests to verify.'));
269
+ } else {
270
+ executeSpinner.fail(chalk.red('Task execution failed'));
271
+ console.error(chalk.red(`Error: ${executedTask.error || 'Unknown error'}`));
272
+ }
273
+
274
+ await storeTask(executedTask);
275
+ console.log('');
276
+ } catch (error) {
277
+ spinner.fail(chalk.red('Task execution failed'));
278
+ console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));
279
+ console.log('');
280
+ }
281
+ continue;
282
+ }
283
+
284
+ if (task.type === 'spawn') {
285
+ if (!task.file || !task.mode) {
286
+ console.log(chalk.yellow('⚠️ Could not determine file and mode from task'));
287
+ continue;
288
+ }
289
+
290
+ const spinner = ora(`Spawning ${task.mode} agent for ${task.file}...`).start();
291
+ try {
292
+ const result = await executeAgent(task.file, task.mode, { dryRun: false });
293
+
294
+ spinner.succeed(chalk.green(`Agent completed successfully`));
295
+ console.log('');
296
+ console.log(chalk.bold('✅ Results:'));
297
+ console.log(chalk.dim('─'.repeat(50)));
298
+ console.log(`${chalk.bold('File:')} ${task.file}`);
299
+ console.log(`${chalk.bold('Mode:')} ${task.mode}`);
300
+ console.log(`${chalk.bold('Changes:')} ${result.changes} modifications`);
301
+ console.log(`${chalk.bold('Cost:')} $${result.cost.toFixed(4)}`);
302
+ console.log(`${chalk.bold('Efficiency:')} ${result.trace?.efficiency.toFixed(3) || 'N/A'}`);
303
+ console.log('');
304
+
305
+ if (result.changes && result.changes.length > 0) {
306
+ console.log(chalk.green('💡 Changes have been applied. Run tests to verify.'));
307
+ } else {
308
+ console.log(chalk.yellow('ℹ️ No changes were needed.'));
309
+ }
310
+ console.log('');
311
+ } catch (error) {
312
+ spinner.fail(chalk.red('Agent execution failed'));
313
+ console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));
314
+ console.log('');
315
+ }
316
+ continue;
317
+ }
318
+ } catch (error) {
319
+ if (error instanceof Error && error.message.includes('User force closed')) {
320
+ running = false;
321
+ break;
322
+ }
323
+ console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));
324
+ }
325
+ }
326
+
327
+ console.log('');
328
+ console.log(chalk.green('🍄 Mycelium network dormant. Growth complete.'));
329
+ console.log('');
330
+ }
331
+
332
+ /**
333
+ * Commander.js command definition
334
+ */
335
+ const command = new Command()
336
+ .name('grow')
337
+ .description('Start interactive mycelium growth interface')
338
+ .option('--task <description>', 'Run a single task and exit')
339
+ .action(async (options: { task?: string }) => {
340
+ if (options.task) {
341
+ // Non-interactive mode - single task
342
+ const task = parseTask(options.task);
343
+
344
+ if (task.type === 'task' && task.description) {
345
+ const spinner = ora('Planning task...').start();
346
+ try {
347
+ // Create and execute task
348
+ const newTask: Task = {
349
+ id: randomUUID(),
350
+ description: task.description,
351
+ status: 'planning',
352
+ created_at: new Date().toISOString(),
353
+ acceptance_criteria: [],
354
+ steps_completed: 0,
355
+ steps_total: 0,
356
+ files_created: [],
357
+ files_modified: [],
358
+ traces: [],
359
+ };
360
+
361
+ const plan = await planTask(newTask);
362
+ newTask.plan = plan;
363
+ newTask.steps_total = plan.steps.length;
364
+ newTask.status = 'in_progress';
365
+ await storeTask(newTask);
366
+
367
+ spinner.text = 'Executing task...';
368
+ const executedTask = await executeTask(newTask);
369
+ await storeTask(executedTask);
370
+
371
+ if (executedTask.status === 'completed') {
372
+ spinner.succeed(chalk.green('Task completed'));
373
+ console.log(`Steps: ${executedTask.steps_completed}/${executedTask.steps_total}, Created: ${executedTask.files_created.length}, Modified: ${executedTask.files_modified.length}`);
374
+ } else {
375
+ spinner.fail(chalk.red('Task failed'));
376
+ console.error(chalk.red(`Error: ${executedTask.error || 'Unknown error'}`));
377
+ process.exit(1);
378
+ }
379
+ } catch (error) {
380
+ spinner.fail(chalk.red('Task failed'));
381
+ console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));
382
+ process.exit(1);
383
+ }
384
+ } else if (task.type === 'spawn' && task.file && task.mode) {
385
+ const spinner = ora(`Spawning ${task.mode} agent...`).start();
386
+ try {
387
+ const result = await executeAgent(task.file, task.mode, { dryRun: false });
388
+ spinner.succeed(chalk.green('Agent completed'));
389
+ console.log(`Changes: ${result.changes}, Cost: $${result.cost.toFixed(4)}, Efficiency: ${result.trace?.efficiency.toFixed(3) || 'N/A'}`);
390
+ } catch (error) {
391
+ spinner.fail(chalk.red('Agent failed'));
392
+ console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));
393
+ process.exit(1);
394
+ }
395
+ } else if (task.type === 'analyze' && task.file) {
396
+ const spinner = ora(`Analyzing ${task.file}...`).start();
397
+ try {
398
+ const gradient = await calculateGradient(task.file);
399
+ spinner.succeed(chalk.green('Analysis complete'));
400
+ console.log(`Score: ${gradient.score.toFixed(3)}, Dominant: ${gradient.dominantSignal.name}`);
401
+ } catch (error) {
402
+ spinner.fail(chalk.red('Analysis failed'));
403
+ console.error(chalk.red(`Error: ${error instanceof Error ? error.message : 'Unknown error'}`));
404
+ process.exit(1);
405
+ }
406
+ } else {
407
+ console.log(chalk.yellow('Could not parse task. Use interactive mode for help.'));
408
+ process.exit(1);
409
+ }
410
+ } else {
411
+ // Interactive TUI mode
412
+ await startGrowSession();
413
+ }
414
+ });
415
+
416
+ export default command;
package/src/cli/index.ts CHANGED
@@ -54,12 +54,14 @@ export async function registerCommands() {
54
54
  const { default: status } = await import('./status.js');
55
55
  const { default: init } = await import('./init.js');
56
56
  const { default: gc } = await import('./gc.js');
57
+ const { default: grow } = await import('./grow.js');
57
58
 
58
59
  program.addCommand(gradients);
59
60
  program.addCommand(cost);
60
61
  program.addCommand(status);
61
62
  program.addCommand(init);
62
63
  program.addCommand(gc);
64
+ program.addCommand(grow);
63
65
  }
64
66
 
65
67
  /**
@@ -27,18 +27,23 @@ import { ciProvider } from '../utils/ci-provider.js';
27
27
  export interface AgentRunResult {
28
28
  success: boolean;
29
29
  changes: string[]; // Files modified
30
- trace: TraceEvent;
30
+ trace?: TraceEvent; // Optional: may not exist on failure
31
31
  cost: number; // USD
32
+ error?: string; // Optional: error message on failure
32
33
  }
33
34
 
34
35
  export interface AgentExecuteOptions {
35
36
  dryRun?: boolean;
36
37
  maxRetries?: number;
38
+ agentId?: string; // Optional: for task-driven execution
39
+ taskId?: string; // Optional: for task-driven execution
37
40
  }
38
41
 
39
- const DEFAULT_OPTIONS: Required<AgentExecuteOptions> = {
42
+ const DEFAULT_OPTIONS = {
40
43
  dryRun: false,
41
44
  maxRetries: 3,
45
+ agentId: undefined,
46
+ taskId: undefined,
42
47
  };
43
48
 
44
49
  /**
@@ -51,7 +56,7 @@ export async function executeAgent(
51
56
  options?: AgentExecuteOptions
52
57
  ): Promise<AgentRunResult> {
53
58
  const opts = { ...DEFAULT_OPTIONS, ...options };
54
- const agentId = `agent-${uuid().slice(0, 8)}`;
59
+ const agentId = opts.agentId || `agent-${uuid().slice(0, 8)}`;
55
60
  const traceId = uuid();
56
61
 
57
62
  logInfo('Starting agent execution', {
@@ -174,6 +179,7 @@ export async function executeAgent(
174
179
  `Gradient improved: ${gradientDelta < 0 ? 'Yes' : 'No'}`,
175
180
  ],
176
181
  agent_id: agentId,
182
+ task_id: opts.taskId, // Link to task if part of task execution
177
183
  cost: costRecord,
178
184
  };
179
185
 
@@ -233,7 +239,14 @@ export async function executeAgent(
233
239
  await recordTrace(errorTrace);
234
240
  }
235
241
 
236
- throw error;
242
+ // Return failure result instead of throwing (for task-worker compatibility)
243
+ return {
244
+ success: false,
245
+ changes: [],
246
+ trace: errorTrace,
247
+ cost: 0,
248
+ error: errorObj.message,
249
+ };
237
250
  }
238
251
  }
239
252