oneie 1.2.2 → 1.2.4

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.
@@ -0,0 +1,499 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Agent Integration System
5
+ * Coordinates between tasks and the 43+ specialized agents
6
+ */
7
+
8
+ import fs from 'fs-extra';
9
+ import path from 'path';
10
+ import yaml from 'js-yaml';
11
+ import chalk from 'chalk';
12
+ import { TaskSystem } from './task-system.js';
13
+
14
+ export class AgentIntegration {
15
+ constructor(projectPath = process.cwd()) {
16
+ this.projectPath = projectPath;
17
+ this.agentsDir = path.join(projectPath, '.claude', 'agents');
18
+ this.taskSystem = new TaskSystem(projectPath);
19
+
20
+ // Command structure - the three main orchestrators
21
+ this.commanders = {
22
+ 'Mission Commander': {
23
+ file: 'mission-commander.md',
24
+ role: 'strategic planning and mission orchestration',
25
+ handoffTo: 'Story Teller'
26
+ },
27
+ 'Story Teller': {
28
+ file: 'story-teller.md',
29
+ role: 'story creation and narrative development',
30
+ handoffTo: 'Task Master'
31
+ },
32
+ 'Task Master': {
33
+ file: 'task-master.md',
34
+ role: 'task execution and agent coordination',
35
+ handoffTo: 'specialists'
36
+ }
37
+ };
38
+
39
+ // Agent teams organized by function
40
+ this.agentTeams = {
41
+ engineering: [
42
+ 'Engineering Director',
43
+ 'Engineering Architect',
44
+ 'Engineering Developer',
45
+ 'Engineering Quality Assurance',
46
+ 'Engineering Product Manager',
47
+ 'Engineering User Experience'
48
+ ],
49
+ marketing: [
50
+ 'Marketing Director',
51
+ 'Marketing Viral Growth',
52
+ 'Marketing Brand Identity',
53
+ 'Marketing Content Hooks',
54
+ 'Marketing Lead Capture',
55
+ 'Marketing Lead Magnet',
56
+ 'Marketing Network Effects'
57
+ ],
58
+ content: [
59
+ 'Content Team Manager',
60
+ 'Content Calendar Planner',
61
+ 'Content Playbook Writer'
62
+ ],
63
+ research: [
64
+ 'Research Team Manager',
65
+ 'Research Foundation Analyst',
66
+ 'Research Market Analyst'
67
+ ],
68
+ service: [
69
+ 'Service Team Manager',
70
+ 'Service Success Manager',
71
+ 'Service Advocacy Manager'
72
+ ],
73
+ crypto: [
74
+ 'Crypto Team Manager',
75
+ 'Crypto Token Analyst',
76
+ 'Crypto Market Researcher'
77
+ ]
78
+ };
79
+ }
80
+
81
+ async executeTask(taskId, options = {}) {
82
+ console.log(chalk.blue(`\\nšŸ¤– Executing task ${taskId}...`));
83
+
84
+ // Get task details
85
+ const task = await this.taskSystem.getTask(taskId);
86
+ if (!task) {
87
+ throw new Error(`Task not found: ${taskId}`);
88
+ }
89
+
90
+ console.log(chalk.cyan(`šŸ“‹ Task: ${task.name}`));
91
+ console.log(chalk.cyan(`šŸ¤– Assigned agents: ${task.agents.join(', ')}`));
92
+
93
+ // Start task if not already active
94
+ if (task.status === 'pending') {
95
+ await this.taskSystem.updateTaskStatus(taskId, 'active', 'Task execution started by agent integration');
96
+ console.log(chalk.yellow('šŸš€ Task status updated to active'));
97
+ }
98
+
99
+ // Create execution plan
100
+ const executionPlan = await this.createExecutionPlan(task);
101
+ console.log(chalk.cyan(`\\nšŸ“‹ Execution plan created with ${executionPlan.phases.length} phases`));
102
+
103
+ // Execute phases
104
+ for (let i = 0; i < executionPlan.phases.length; i++) {
105
+ const phase = executionPlan.phases[i];
106
+ console.log(chalk.yellow(`\\n⚔ Phase ${i + 1}: ${phase.name}`));
107
+
108
+ const result = await this.executePhase(phase, task, options);
109
+
110
+ if (result.success) {
111
+ console.log(chalk.green(`āœ… Phase ${i + 1} completed successfully`));
112
+ } else {
113
+ console.log(chalk.red(`āŒ Phase ${i + 1} failed: ${result.error}`));
114
+ await this.taskSystem.updateTaskStatus(taskId, 'blocked', `Phase ${i + 1} failed: ${result.error}`);
115
+ return { success: false, error: result.error };
116
+ }
117
+ }
118
+
119
+ // Mark task as completed
120
+ await this.taskSystem.updateTaskStatus(taskId, 'completed', 'Task completed by agent integration');
121
+ console.log(chalk.green(`\\nšŸŽ‰ Task "${task.name}" completed successfully!`));
122
+
123
+ return { success: true, executionPlan };
124
+ }
125
+
126
+ async createExecutionPlan(task) {
127
+ const plan = {
128
+ taskId: task.id,
129
+ taskName: task.name,
130
+ phases: [],
131
+ totalEstimatedTime: task.duration
132
+ };
133
+
134
+ const taskType = this.identifyTaskType(task);
135
+
136
+ switch (taskType) {
137
+ case 'implementation':
138
+ plan.phases = [
139
+ { name: 'Planning & Design', agents: ['Engineering Architect', 'Engineering Director'], duration: '1 hour' },
140
+ { name: 'Implementation', agents: ['Engineering Developer'], duration: '3 hours' },
141
+ { name: 'Testing & Validation', agents: ['Engineering Quality Assurance'], duration: '1 hour' },
142
+ { name: 'Review & Documentation', agents: ['Task Master'], duration: '30 minutes' }
143
+ ];
144
+ break;
145
+
146
+ case 'design':
147
+ plan.phases = [
148
+ { name: 'Requirements Analysis', agents: ['Engineering User Experience', 'Engineering Product Manager'], duration: '1 hour' },
149
+ { name: 'UI/UX Design', agents: ['Engineering User Experience'], duration: '2 hours' },
150
+ { name: 'Design Review', agents: ['Engineering Architect', 'Engineering Director'], duration: '30 minutes' },
151
+ { name: 'Documentation', agents: ['Task Master'], duration: '30 minutes' }
152
+ ];
153
+ break;
154
+
155
+ case 'research':
156
+ plan.phases = [
157
+ { name: 'Research Planning', agents: ['Research Team Manager'], duration: '30 minutes' },
158
+ { name: 'Data Collection', agents: ['Research Foundation Analyst', 'Research Market Analyst'], duration: '2 hours' },
159
+ { name: 'Analysis & Insights', agents: ['Research Team Manager'], duration: '1 hour' },
160
+ { name: 'Report Generation', agents: ['Content Playbook Writer'], duration: '30 minutes' }
161
+ ];
162
+ break;
163
+
164
+ case 'marketing':
165
+ plan.phases = [
166
+ { name: 'Strategy Planning', agents: ['Marketing Director'], duration: '1 hour' },
167
+ { name: 'Content Creation', agents: ['Marketing Content Hooks', 'Content Team Manager'], duration: '2 hours' },
168
+ { name: 'Campaign Setup', agents: ['Marketing Viral Growth'], duration: '1 hour' },
169
+ { name: 'Launch & Monitoring', agents: ['Task Master'], duration: '30 minutes' }
170
+ ];
171
+ break;
172
+
173
+ default:
174
+ // Generic execution plan
175
+ plan.phases = [
176
+ { name: 'Planning', agents: ['Task Master'], duration: '30 minutes' },
177
+ { name: 'Execution', agents: task.agents.filter(a => a !== 'Task Master'), duration: '3 hours' },
178
+ { name: 'Validation', agents: ['Task Master'], duration: '30 minutes' }
179
+ ];
180
+ }
181
+
182
+ return plan;
183
+ }
184
+
185
+ identifyTaskType(task) {
186
+ const taskLower = task.name.toLowerCase();
187
+ const description = task.description?.toLowerCase() || '';
188
+
189
+ if (taskLower.includes('implement') || taskLower.includes('code') || taskLower.includes('develop')) {
190
+ return 'implementation';
191
+ }
192
+
193
+ if (taskLower.includes('design') || taskLower.includes('ui') || taskLower.includes('ux')) {
194
+ return 'design';
195
+ }
196
+
197
+ if (taskLower.includes('research') || taskLower.includes('analyze') || taskLower.includes('investigate')) {
198
+ return 'research';
199
+ }
200
+
201
+ if (taskLower.includes('marketing') || taskLower.includes('campaign') || taskLower.includes('growth')) {
202
+ return 'marketing';
203
+ }
204
+
205
+ if (taskLower.includes('test') || taskLower.includes('quality')) {
206
+ return 'testing';
207
+ }
208
+
209
+ if (taskLower.includes('content') || taskLower.includes('write') || taskLower.includes('document')) {
210
+ return 'content';
211
+ }
212
+
213
+ return 'generic';
214
+ }
215
+
216
+ async executePhase(phase, task, options = {}) {
217
+ console.log(chalk.gray(` šŸ”§ Phase: ${phase.name}`));
218
+ console.log(chalk.gray(` šŸ‘„ Agents: ${phase.agents.join(', ')}`));
219
+ console.log(chalk.gray(` ā±ļø Duration: ${phase.duration}`));
220
+
221
+ try {
222
+ // Simulate agent work based on phase type
223
+ const phaseResult = await this.simulateAgentWork(phase, task, options);
224
+
225
+ // Add phase completion note to task
226
+ await this.taskSystem.updateTaskStatus(
227
+ task.id,
228
+ task.status,
229
+ `Phase "${phase.name}" completed by ${phase.agents.join(', ')}`
230
+ );
231
+
232
+ return { success: true, result: phaseResult };
233
+ } catch (error) {
234
+ console.error(chalk.red(` āŒ Phase failed: ${error.message}`));
235
+ return { success: false, error: error.message };
236
+ }
237
+ }
238
+
239
+ async simulateAgentWork(phase, task, options = {}) {
240
+ // In a real implementation, this would integrate with actual agent execution
241
+ // For now, we simulate the work and provide realistic output
242
+
243
+ const phaseName = phase.name.toLowerCase();
244
+ const taskName = task.name.toLowerCase();
245
+
246
+ if (options.simulate !== false) {
247
+ // Simulate work delay
248
+ await new Promise(resolve => setTimeout(resolve, 500));
249
+ }
250
+
251
+ // Generate phase-specific outputs
252
+ let output = {};
253
+
254
+ if (phaseName.includes('planning')) {
255
+ output = {
256
+ type: 'planning_document',
257
+ content: `Planning document for ${task.name}`,
258
+ deliverables: ['Requirements specification', 'Technical approach', 'Resource allocation'],
259
+ nextSteps: ['Proceed to implementation phase']
260
+ };
261
+ } else if (phaseName.includes('implementation')) {
262
+ output = {
263
+ type: 'code_implementation',
264
+ content: `Implementation of ${task.name}`,
265
+ deliverables: ['Working code', 'Unit tests', 'Integration points'],
266
+ nextSteps: ['Code review and testing']
267
+ };
268
+ } else if (phaseName.includes('design')) {
269
+ output = {
270
+ type: 'design_specification',
271
+ content: `Design specification for ${task.name}`,
272
+ deliverables: ['UI mockups', 'Component specifications', 'Design guidelines'],
273
+ nextSteps: ['Implementation planning']
274
+ };
275
+ } else if (phaseName.includes('testing')) {
276
+ output = {
277
+ type: 'test_results',
278
+ content: `Test results for ${task.name}`,
279
+ deliverables: ['Test cases', 'Test execution results', 'Quality metrics'],
280
+ nextSteps: ['Production deployment preparation']
281
+ };
282
+ } else {
283
+ output = {
284
+ type: 'generic_output',
285
+ content: `${phase.name} completed for ${task.name}`,
286
+ deliverables: ['Phase deliverables'],
287
+ nextSteps: ['Continue to next phase']
288
+ };
289
+ }
290
+
291
+ console.log(chalk.gray(` šŸ“„ Generated: ${output.content}`));
292
+ console.log(chalk.gray(` šŸ“¦ Deliverables: ${output.deliverables.join(', ')}`));
293
+
294
+ return output;
295
+ }
296
+
297
+ async getAgentCapabilities(agentName) {
298
+ const agentFile = path.join(this.agentsDir, `${agentName.toLowerCase().replace(/\\s+/g, '-')}.md`);
299
+
300
+ if (await fs.pathExists(agentFile)) {
301
+ const content = await fs.readFile(agentFile, 'utf8');
302
+
303
+ // Parse YAML frontmatter
304
+ const frontMatterMatch = content.match(/^---\\n([\\s\\S]*?)\\n---/);
305
+ if (frontMatterMatch) {
306
+ try {
307
+ const frontMatter = yaml.load(frontMatterMatch[1]);
308
+ return {
309
+ name: frontMatter.name,
310
+ description: frontMatter.description,
311
+ tools: frontMatter.tools || [],
312
+ color: frontMatter.color || 'white'
313
+ };
314
+ } catch (error) {
315
+ console.warn(chalk.yellow(`Warning: Could not parse frontmatter for ${agentName}`));
316
+ }
317
+ }
318
+ }
319
+
320
+ return {
321
+ name: agentName,
322
+ description: `Specialized agent: ${agentName}`,
323
+ tools: [],
324
+ color: 'white'
325
+ };
326
+ }
327
+
328
+ async cascadeWorkflow(missionId, options = {}) {
329
+ console.log(chalk.cyan.bold(`\\n🌊 Starting cascade workflow for mission ${missionId}...`));
330
+
331
+ // Phase 1: Mission Commander creates stories
332
+ console.log(chalk.yellow('\\nšŸ‘‘ Phase 1: Mission Commander - Story Spawning'));
333
+ const mission = await this.getMission(missionId);
334
+ if (!mission) {
335
+ throw new Error(`Mission not found: ${missionId}`);
336
+ }
337
+
338
+ console.log(chalk.cyan(`šŸ“‹ Mission: ${mission.name}`));
339
+ console.log(chalk.cyan(`šŸŽÆ Objective: ${mission.objective}`));
340
+
341
+ // Phase 2: Story Teller develops narratives and creates tasks
342
+ console.log(chalk.green('\\nšŸ“š Phase 2: Story Teller - Task Generation'));
343
+ const stories = await this.getStoriesForMission(missionId);
344
+
345
+ for (const story of stories) {
346
+ console.log(chalk.cyan(` šŸ“– Processing story: ${story.name}`));
347
+
348
+ // Ensure story has tasks
349
+ if (!story.tasks || story.tasks.length === 0) {
350
+ console.log(chalk.yellow(` šŸ“‹ Generating tasks for story ${story.id}...`));
351
+ // In a real implementation, Story Teller would create tasks here
352
+ console.log(chalk.gray(` āœ… Tasks would be generated by Story Teller agent`));
353
+ }
354
+ }
355
+
356
+ // Phase 3: Task Master orchestrates execution
357
+ console.log(chalk.blue('\\n⚔ Phase 3: Task Master - Execution Orchestration'));
358
+
359
+ for (const story of stories) {
360
+ if (story.tasks && story.tasks.length > 0) {
361
+ console.log(chalk.cyan(` šŸ“– Story: ${story.name}`));
362
+
363
+ for (const taskRef of story.tasks) {
364
+ const taskId = typeof taskRef === 'object' ? taskRef.id : taskRef;
365
+ const task = await this.taskSystem.getTask(taskId);
366
+
367
+ if (task && task.status === 'pending') {
368
+ console.log(chalk.yellow(` šŸ“‹ Orchestrating task: ${task.name}`));
369
+
370
+ if (options.execute) {
371
+ const result = await this.executeTask(taskId, { simulate: true });
372
+ if (result.success) {
373
+ console.log(chalk.green(` āœ… Task completed`));
374
+ } else {
375
+ console.log(chalk.red(` āŒ Task failed: ${result.error}`));
376
+ }
377
+ } else {
378
+ console.log(chalk.gray(` šŸ“‹ Task ready for execution`));
379
+ }
380
+ }
381
+ }
382
+ }
383
+ }
384
+
385
+ console.log(chalk.green.bold('\\nšŸŽ‰ Cascade workflow completed!'));
386
+
387
+ return {
388
+ mission,
389
+ stories,
390
+ totalTasks: stories.reduce((sum, story) => sum + (story.tasks?.length || 0), 0),
391
+ completedPhases: ['Mission Commander', 'Story Teller', 'Task Master']
392
+ };
393
+ }
394
+
395
+ async getMission(missionId) {
396
+ const missionPath = path.join(this.taskSystem.missionsDir, missionId, 'mission.yaml');
397
+ if (await fs.pathExists(missionPath)) {
398
+ return yaml.load(await fs.readFile(missionPath, 'utf8'));
399
+ }
400
+ return null;
401
+ }
402
+
403
+ async getStoriesForMission(missionId) {
404
+ const stories = [];
405
+ const storiesDir = path.join(this.taskSystem.missionsDir, missionId, 'stories');
406
+
407
+ if (await fs.pathExists(storiesDir)) {
408
+ const files = await fs.readdir(storiesDir);
409
+
410
+ for (const file of files) {
411
+ if (file.endsWith('.yaml') && file !== 'tasks') {
412
+ const storyPath = path.join(storiesDir, file);
413
+ const story = yaml.load(await fs.readFile(storyPath, 'utf8'));
414
+ stories.push(story);
415
+ }
416
+ }
417
+ }
418
+
419
+ return stories;
420
+ }
421
+
422
+ async getAgentWorkload() {
423
+ const tasks = await this.taskSystem.listTasks();
424
+ const activeTasks = tasks.filter(task => task.status === 'active');
425
+
426
+ const workload = {};
427
+
428
+ activeTasks.forEach(task => {
429
+ task.agents.forEach(agent => {
430
+ if (!workload[agent]) {
431
+ workload[agent] = {
432
+ activeTasks: 0,
433
+ tasks: []
434
+ };
435
+ }
436
+ workload[agent].activeTasks++;
437
+ workload[agent].tasks.push({
438
+ id: task.id,
439
+ name: task.name,
440
+ priority: task.priority
441
+ });
442
+ });
443
+ });
444
+
445
+ return workload;
446
+ }
447
+
448
+ async recommendOptimalAgent(taskType, currentWorkload = null) {
449
+ if (!currentWorkload) {
450
+ currentWorkload = await this.getAgentWorkload();
451
+ }
452
+
453
+ let candidateAgents = [];
454
+
455
+ switch (taskType) {
456
+ case 'implementation':
457
+ candidateAgents = this.agentTeams.engineering.filter(agent =>
458
+ agent.includes('Developer') || agent.includes('Engineer'));
459
+ break;
460
+ case 'design':
461
+ candidateAgents = this.agentTeams.engineering.filter(agent =>
462
+ agent.includes('User Experience') || agent.includes('Architect'));
463
+ break;
464
+ case 'research':
465
+ candidateAgents = this.agentTeams.research;
466
+ break;
467
+ case 'marketing':
468
+ candidateAgents = this.agentTeams.marketing;
469
+ break;
470
+ default:
471
+ candidateAgents = ['Task Master'];
472
+ }
473
+
474
+ // Sort by current workload (ascending - less loaded agents first)
475
+ candidateAgents.sort((a, b) => {
476
+ const aLoad = currentWorkload[a]?.activeTasks || 0;
477
+ const bLoad = currentWorkload[b]?.activeTasks || 0;
478
+ return aLoad - bLoad;
479
+ });
480
+
481
+ return candidateAgents[0] || 'Task Master';
482
+ }
483
+ }
484
+
485
+ // CLI interface functions
486
+ export async function executeTask(taskId, options = {}) {
487
+ const agentIntegration = new AgentIntegration();
488
+ return await agentIntegration.executeTask(taskId, options);
489
+ }
490
+
491
+ export async function cascadeWorkflow(missionId, options = {}) {
492
+ const agentIntegration = new AgentIntegration();
493
+ return await agentIntegration.cascadeWorkflow(missionId, options);
494
+ }
495
+
496
+ export async function getAgentWorkload() {
497
+ const agentIntegration = new AgentIntegration();
498
+ return await agentIntegration.getAgentWorkload();
499
+ }