oneie 1.2.1 → 1.2.2

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,612 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Mission Creation and Management System
5
+ * Core system for creating, managing, and executing missions with human-AI collaboration
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 inquirer from 'inquirer';
13
+
14
+ export class MissionSystem {
15
+ constructor(projectPath = process.cwd()) {
16
+ this.projectPath = projectPath;
17
+ this.oneDir = path.join(projectPath, '.one');
18
+ this.missionsDir = path.join(this.oneDir, 'missions');
19
+ this.storiesDir = path.join(this.oneDir, 'stories');
20
+ this.tasksDir = path.join(this.oneDir, 'tasks');
21
+ }
22
+
23
+ async createMission(objective, options = {}) {
24
+ console.log(chalk.blue('\nšŸŽÆ Creating new mission...'));
25
+
26
+ // Step 1: Analyze project architecture
27
+ const architecture = await this.analyzeArchitecture();
28
+
29
+ // Step 2: Generate mission template
30
+ const missionTemplate = await this.generateMissionTemplate(objective, architecture);
31
+
32
+ // Step 3: Human-AI collaboration on mission design
33
+ const mission = await this.collaborativelyDesignMission(missionTemplate, options);
34
+
35
+ // Step 4: Create mission file and directory structure
36
+ await this.initializeMission(mission);
37
+
38
+ // Step 5: Generate initial stories
39
+ await this.generateInitialStories(mission);
40
+
41
+ console.log(chalk.green(`\nāœ… Mission "${mission.name}" created successfully!`));
42
+ console.log(chalk.cyan(`šŸ“ Mission directory: .one/missions/${mission.id}/`));
43
+
44
+ return mission;
45
+ }
46
+
47
+ async analyzeArchitecture() {
48
+ console.log(chalk.gray('šŸ” Analyzing project architecture...'));
49
+
50
+ const architecture = {
51
+ techStack: await this.detectTechStack(),
52
+ projectStructure: await this.analyzeProjectStructure(),
53
+ existingMissions: await this.getExistingMissions(),
54
+ integrationPoints: await this.findIntegrationPoints()
55
+ };
56
+
57
+ console.log(chalk.green('āœ… Architecture analysis complete'));
58
+ return architecture;
59
+ }
60
+
61
+ async detectTechStack() {
62
+ const techStack = {
63
+ languages: [],
64
+ frameworks: [],
65
+ databases: [],
66
+ cloud: [],
67
+ tools: []
68
+ };
69
+
70
+ const detectors = [
71
+ { file: 'package.json', handler: this.detectJavaScriptStack },
72
+ { file: 'requirements.txt', handler: this.detectPythonStack },
73
+ { file: 'pom.xml', handler: this.detectJavaStack },
74
+ { file: 'go.mod', handler: this.detectGoStack },
75
+ { file: 'Cargo.toml', handler: this.detectRustStack },
76
+ { file: 'composer.json', handler: this.detectPHPStack }
77
+ ];
78
+
79
+ for (const detector of detectors) {
80
+ const filePath = path.join(this.projectPath, detector.file);
81
+ if (await fs.pathExists(filePath)) {
82
+ const detected = await detector.handler.call(this, filePath);
83
+ this.mergeTechStack(techStack, detected);
84
+ }
85
+ }
86
+
87
+ return techStack;
88
+ }
89
+
90
+ async detectJavaScriptStack(packagePath) {
91
+ const packageJson = await fs.readJson(packagePath);
92
+ const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
93
+
94
+ const techStack = {
95
+ languages: ['JavaScript'],
96
+ frameworks: [],
97
+ databases: [],
98
+ tools: []
99
+ };
100
+
101
+ // Detect frameworks
102
+ if (deps.react) techStack.frameworks.push('React');
103
+ if (deps.vue) techStack.frameworks.push('Vue');
104
+ if (deps.angular) techStack.frameworks.push('Angular');
105
+ if (deps.express) techStack.frameworks.push('Express');
106
+ if (deps.next) techStack.frameworks.push('Next.js');
107
+ if (deps.nuxt) techStack.frameworks.push('Nuxt.js');
108
+
109
+ // Detect databases
110
+ if (deps.mongodb || deps.mongoose) techStack.databases.push('MongoDB');
111
+ if (deps.pg || deps['node-postgres']) techStack.databases.push('PostgreSQL');
112
+ if (deps.mysql || deps.mysql2) techStack.databases.push('MySQL');
113
+ if (deps.sqlite3) techStack.databases.push('SQLite');
114
+
115
+ // Detect tools
116
+ if (deps.typescript) {
117
+ techStack.languages.push('TypeScript');
118
+ techStack.tools.push('TypeScript');
119
+ }
120
+ if (deps.webpack) techStack.tools.push('Webpack');
121
+ if (deps.vite) techStack.tools.push('Vite');
122
+ if (deps.jest) techStack.tools.push('Jest');
123
+
124
+ return techStack;
125
+ }
126
+
127
+ async detectPythonStack(requirementsPath) {
128
+ const requirements = await fs.readFile(requirementsPath, 'utf8');
129
+ const techStack = {
130
+ languages: ['Python'],
131
+ frameworks: [],
132
+ databases: [],
133
+ tools: []
134
+ };
135
+
136
+ // Detect frameworks
137
+ if (requirements.includes('django')) techStack.frameworks.push('Django');
138
+ if (requirements.includes('flask')) techStack.frameworks.push('Flask');
139
+ if (requirements.includes('fastapi')) techStack.frameworks.push('FastAPI');
140
+ if (requirements.includes('streamlit')) techStack.frameworks.push('Streamlit');
141
+
142
+ // Detect databases
143
+ if (requirements.includes('psycopg2') || requirements.includes('postgresql')) techStack.databases.push('PostgreSQL');
144
+ if (requirements.includes('pymongo')) techStack.databases.push('MongoDB');
145
+ if (requirements.includes('sqlite')) techStack.databases.push('SQLite');
146
+
147
+ // Detect ML/AI tools
148
+ if (requirements.includes('tensorflow')) techStack.tools.push('TensorFlow');
149
+ if (requirements.includes('pytorch')) techStack.tools.push('PyTorch');
150
+ if (requirements.includes('pandas')) techStack.tools.push('Pandas');
151
+ if (requirements.includes('numpy')) techStack.tools.push('NumPy');
152
+
153
+ return techStack;
154
+ }
155
+
156
+ mergeTechStack(target, source) {
157
+ for (const [key, values] of Object.entries(source)) {
158
+ if (Array.isArray(values)) {
159
+ target[key] = [...new Set([...target[key], ...values])];
160
+ }
161
+ }
162
+ }
163
+
164
+ async analyzeProjectStructure() {
165
+ const structure = {
166
+ type: 'unknown',
167
+ patterns: [],
168
+ complexity: 'medium',
169
+ hasTests: false,
170
+ hasDocker: false,
171
+ hasCI: false
172
+ };
173
+
174
+ // Detect project type
175
+ const files = await fs.readdir(this.projectPath);
176
+
177
+ if (files.includes('src') && files.includes('public')) {
178
+ structure.type = 'frontend';
179
+ structure.patterns.push('SPA');
180
+ } else if (files.includes('server.js') || files.includes('app.js')) {
181
+ structure.type = 'backend';
182
+ structure.patterns.push('API');
183
+ } else if (files.includes('src') && files.includes('package.json')) {
184
+ structure.type = 'fullstack';
185
+ structure.patterns.push('monorepo');
186
+ }
187
+
188
+ // Detect additional patterns
189
+ if (files.includes('docker-compose.yml')) {
190
+ structure.hasDocker = true;
191
+ structure.patterns.push('containerized');
192
+ }
193
+
194
+ if (files.includes('.github') || files.includes('.gitlab-ci.yml')) {
195
+ structure.hasCI = true;
196
+ structure.patterns.push('ci_cd');
197
+ }
198
+
199
+ // Check for test directories
200
+ if (files.some(f => f.includes('test') || f.includes('spec'))) {
201
+ structure.hasTests = true;
202
+ }
203
+
204
+ return structure;
205
+ }
206
+
207
+ async generateMissionTemplate(objective, architecture) {
208
+ console.log(chalk.gray('🧠 Generating mission template...'));
209
+
210
+ const template = {
211
+ name: this.generateMissionName(objective),
212
+ id: this.generateMissionId(objective),
213
+ objective: objective,
214
+ architecture: architecture,
215
+ suggestedAgents: this.suggestAgents(architecture),
216
+ suggestedStories: this.suggestStories(objective, architecture),
217
+ estimatedDuration: this.estimateDuration(objective, architecture),
218
+ complexity: this.assessComplexity(objective, architecture)
219
+ };
220
+
221
+ return template;
222
+ }
223
+
224
+ generateMissionName(objective) {
225
+ // Convert objective to mission name
226
+ return objective
227
+ .toLowerCase()
228
+ .replace(/[^a-z0-9\s]/g, '')
229
+ .replace(/\s+/g, '-')
230
+ .substring(0, 50);
231
+ }
232
+
233
+ generateMissionId(objective) {
234
+ const timestamp = Date.now();
235
+ const hash = this.hashString(objective).substring(0, 8);
236
+ return `mission-${hash}-${timestamp}`;
237
+ }
238
+
239
+ hashString(str) {
240
+ let hash = 0;
241
+ for (let i = 0; i < str.length; i++) {
242
+ const char = str.charCodeAt(i);
243
+ hash = ((hash << 5) - hash) + char;
244
+ hash = hash & hash; // Convert to 32-bit integer
245
+ }
246
+ return Math.abs(hash).toString(16);
247
+ }
248
+
249
+ suggestAgents(architecture) {
250
+ const agents = [];
251
+
252
+ // Base agents for all missions
253
+ agents.push('Mission Commander', 'Task Master');
254
+
255
+ // Add agents based on tech stack
256
+ if (architecture.techStack.frameworks.includes('React')) {
257
+ agents.push('React Specialist', 'Frontend Developer');
258
+ }
259
+
260
+ if (architecture.techStack.frameworks.includes('Express')) {
261
+ agents.push('Backend Developer', 'API Designer');
262
+ }
263
+
264
+ if (architecture.techStack.languages.includes('Python')) {
265
+ agents.push('Python Developer', 'Data Analyst');
266
+ }
267
+
268
+ if (architecture.techStack.databases.length > 0) {
269
+ agents.push('Database Specialist');
270
+ }
271
+
272
+ if (architecture.projectStructure.hasDocker) {
273
+ agents.push('DevOps Engineer');
274
+ }
275
+
276
+ if (architecture.projectStructure.hasTests) {
277
+ agents.push('Quality Assurance Engineer');
278
+ }
279
+
280
+ return agents;
281
+ }
282
+
283
+ suggestStories(objective, architecture) {
284
+ const stories = [];
285
+
286
+ // Generate stories based on objective keywords
287
+ const objectiveLower = objective.toLowerCase();
288
+
289
+ if (objectiveLower.includes('api') || objectiveLower.includes('backend')) {
290
+ stories.push('api-development', 'database-integration', 'authentication');
291
+ }
292
+
293
+ if (objectiveLower.includes('ui') || objectiveLower.includes('frontend')) {
294
+ stories.push('component-development', 'user-experience', 'responsive-design');
295
+ }
296
+
297
+ if (objectiveLower.includes('test') || objectiveLower.includes('quality')) {
298
+ stories.push('test-automation', 'quality-assurance', 'performance-testing');
299
+ }
300
+
301
+ if (objectiveLower.includes('deploy') || objectiveLower.includes('production')) {
302
+ stories.push('deployment-automation', 'monitoring-setup', 'security-hardening');
303
+ }
304
+
305
+ // Default stories if none matched
306
+ if (stories.length === 0) {
307
+ stories.push('planning', 'development', 'testing', 'deployment');
308
+ }
309
+
310
+ return stories;
311
+ }
312
+
313
+ estimateDuration(objective, architecture) {
314
+ let baseDuration = 2; // weeks
315
+
316
+ // Adjust based on complexity indicators
317
+ if (architecture.projectStructure.complexity === 'high') baseDuration += 2;
318
+ if (architecture.techStack.frameworks.length > 2) baseDuration += 1;
319
+ if (architecture.projectStructure.hasDocker) baseDuration += 0.5;
320
+
321
+ const complexityKeywords = ['complex', 'enterprise', 'large', 'scale', 'multiple'];
322
+ const hasComplexityKeywords = complexityKeywords.some(keyword =>
323
+ objective.toLowerCase().includes(keyword)
324
+ );
325
+
326
+ if (hasComplexityKeywords) baseDuration += 1;
327
+
328
+ return `${Math.ceil(baseDuration)} weeks`;
329
+ }
330
+
331
+ assessComplexity(objective, architecture) {
332
+ let score = 1; // base complexity
333
+
334
+ score += architecture.techStack.languages.length * 0.5;
335
+ score += architecture.techStack.frameworks.length * 0.3;
336
+ score += architecture.techStack.databases.length * 0.2;
337
+
338
+ if (architecture.projectStructure.hasDocker) score += 0.5;
339
+ if (architecture.projectStructure.hasCI) score += 0.3;
340
+
341
+ const complexityKeywords = ['integrate', 'migrate', 'refactor', 'optimize', 'scale'];
342
+ const matchedKeywords = complexityKeywords.filter(keyword =>
343
+ objective.toLowerCase().includes(keyword)
344
+ ).length;
345
+ score += matchedKeywords * 0.4;
346
+
347
+ if (score <= 2) return 'low';
348
+ if (score <= 3.5) return 'medium';
349
+ return 'high';
350
+ }
351
+
352
+ async collaborativelyDesignMission(template, options) {
353
+ console.log(chalk.blue('\nšŸ¤ Collaborative mission design...'));
354
+
355
+ // Show AI analysis
356
+ console.log(chalk.cyan('\nšŸ¤– AI Analysis:'));
357
+ console.log(` Suggested name: ${template.name}`);
358
+ console.log(` Estimated duration: ${template.estimatedDuration}`);
359
+ console.log(` Complexity: ${template.complexity}`);
360
+ console.log(` Suggested agents: ${template.suggestedAgents.join(', ')}`);
361
+
362
+ if (options.interactive !== false) {
363
+ // Get human input
364
+ const answers = await inquirer.prompt([
365
+ {
366
+ type: 'input',
367
+ name: 'name',
368
+ message: 'Mission name:',
369
+ default: template.name
370
+ },
371
+ {
372
+ type: 'editor',
373
+ name: 'description',
374
+ message: 'Mission description:',
375
+ default: `# ${template.objective}\n\n[Add detailed description of what this mission will accomplish]`
376
+ },
377
+ {
378
+ type: 'checkbox',
379
+ name: 'agents',
380
+ message: 'Select agents for this mission:',
381
+ choices: template.suggestedAgents,
382
+ default: template.suggestedAgents.slice(0, 4) // Select first 4 by default
383
+ },
384
+ {
385
+ type: 'input',
386
+ name: 'duration',
387
+ message: 'Expected duration:',
388
+ default: template.estimatedDuration
389
+ }
390
+ ]);
391
+
392
+ // Merge human input with AI suggestions
393
+ template.name = answers.name;
394
+ template.description = answers.description;
395
+ template.agents = answers.agents;
396
+ template.duration = answers.duration;
397
+ } else {
398
+ // Non-interactive mode - use AI suggestions
399
+ template.agents = template.suggestedAgents.slice(0, 4);
400
+ template.duration = template.estimatedDuration;
401
+ template.description = `# ${template.objective}\n\nAI-generated mission to ${template.objective.toLowerCase()}.`;
402
+ }
403
+
404
+ console.log(chalk.green('āœ… Mission design complete'));
405
+ return template;
406
+ }
407
+
408
+ async initializeMission(mission) {
409
+ console.log(chalk.gray('šŸ“ Creating mission structure...'));
410
+
411
+ // Ensure directories exist
412
+ await fs.ensureDir(this.missionsDir);
413
+
414
+ const missionDir = path.join(this.missionsDir, mission.id);
415
+ await fs.ensureDir(missionDir);
416
+
417
+ // Create mission.yaml file
418
+ const missionData = {
419
+ name: mission.name,
420
+ id: mission.id,
421
+ objective: mission.objective,
422
+ description: mission.description,
423
+ status: 'planning',
424
+ created: new Date().toISOString(),
425
+ agents: mission.agents,
426
+ stories: mission.suggestedStories || [],
427
+ duration: mission.duration,
428
+ complexity: mission.complexity,
429
+ architecture: mission.architecture
430
+ };
431
+
432
+ await fs.writeFile(
433
+ path.join(missionDir, 'mission.yaml'),
434
+ yaml.dump(missionData, { indent: 2 })
435
+ );
436
+
437
+ // Create mission README
438
+ const readmeContent = `# ${mission.name}
439
+
440
+ ${mission.description}
441
+
442
+ ## Objective
443
+ ${mission.objective}
444
+
445
+ ## Agents
446
+ ${mission.agents.map(agent => `- ${agent}`).join('\n')}
447
+
448
+ ## Stories
449
+ ${mission.suggestedStories.map(story => `- [ ] ${story}`).join('\n')}
450
+
451
+ ## Status
452
+ - Created: ${new Date().toISOString()}
453
+ - Status: Planning
454
+ - Duration: ${mission.duration}
455
+ - Complexity: ${mission.complexity}
456
+
457
+ ## Architecture Context
458
+ - Tech Stack: ${JSON.stringify(mission.architecture.techStack, null, 2)}
459
+ - Project Type: ${mission.architecture.projectStructure.type}
460
+ `;
461
+
462
+ await fs.writeFile(path.join(missionDir, 'README.md'), readmeContent);
463
+
464
+ // Create directories for stories and tasks
465
+ await fs.ensureDir(path.join(missionDir, 'stories'));
466
+ await fs.ensureDir(path.join(missionDir, 'tasks'));
467
+ }
468
+
469
+ async generateInitialStories(mission) {
470
+ console.log(chalk.gray('šŸ“š Generating initial stories...'));
471
+
472
+ for (const storyName of mission.suggestedStories) {
473
+ await this.createStory(mission.id, storyName, {
474
+ auto: true,
475
+ agents: mission.agents
476
+ });
477
+ }
478
+ }
479
+
480
+ async createStory(missionId, storyName, options = {}) {
481
+ const storyId = `story-${this.hashString(storyName).substring(0, 8)}`;
482
+ const missionDir = path.join(this.missionsDir, missionId);
483
+ const storiesDir = path.join(missionDir, 'stories');
484
+
485
+ const storyData = {
486
+ name: storyName,
487
+ id: storyId,
488
+ missionId: missionId,
489
+ status: 'planning',
490
+ created: new Date().toISOString(),
491
+ agents: options.agents || [],
492
+ tasks: [],
493
+ description: options.auto
494
+ ? `Auto-generated story for ${storyName} within mission ${missionId}`
495
+ : options.description || ''
496
+ };
497
+
498
+ await fs.writeFile(
499
+ path.join(storiesDir, `${storyId}.yaml`),
500
+ yaml.dump(storyData, { indent: 2 })
501
+ );
502
+
503
+ return storyData;
504
+ }
505
+
506
+ async listMissions() {
507
+ if (!await fs.pathExists(this.missionsDir)) {
508
+ return [];
509
+ }
510
+
511
+ const missionDirs = await fs.readdir(this.missionsDir);
512
+ const missions = [];
513
+
514
+ for (const dir of missionDirs) {
515
+ const missionFile = path.join(this.missionsDir, dir, 'mission.yaml');
516
+ if (await fs.pathExists(missionFile)) {
517
+ const missionData = yaml.load(await fs.readFile(missionFile, 'utf8'));
518
+ missions.push(missionData);
519
+ }
520
+ }
521
+
522
+ return missions;
523
+ }
524
+
525
+ async getMission(missionId) {
526
+ const missionFile = path.join(this.missionsDir, missionId, 'mission.yaml');
527
+ if (await fs.pathExists(missionFile)) {
528
+ return yaml.load(await fs.readFile(missionFile, 'utf8'));
529
+ }
530
+ return null;
531
+ }
532
+
533
+ async getExistingMissions() {
534
+ return await this.listMissions();
535
+ }
536
+
537
+ async findIntegrationPoints() {
538
+ // Simple integration point detection
539
+ const points = [];
540
+
541
+ // Check for common integration patterns
542
+ const commonPaths = [
543
+ 'src/',
544
+ 'lib/',
545
+ 'app/',
546
+ 'components/',
547
+ 'pages/',
548
+ 'routes/',
549
+ 'middleware/',
550
+ 'services/'
551
+ ];
552
+
553
+ for (const pathName of commonPaths) {
554
+ const fullPath = path.join(this.projectPath, pathName);
555
+ if (await fs.pathExists(fullPath)) {
556
+ points.push({
557
+ path: pathName,
558
+ type: this.inferIntegrationType(pathName),
559
+ priority: this.calculateIntegrationPriority(pathName)
560
+ });
561
+ }
562
+ }
563
+
564
+ return points.sort((a, b) => b.priority - a.priority);
565
+ }
566
+
567
+ inferIntegrationType(pathName) {
568
+ const typeMap = {
569
+ 'src/': 'source_code',
570
+ 'lib/': 'library',
571
+ 'app/': 'application',
572
+ 'components/': 'ui_components',
573
+ 'pages/': 'routing',
574
+ 'routes/': 'api_routes',
575
+ 'middleware/': 'middleware',
576
+ 'services/': 'business_logic'
577
+ };
578
+
579
+ return typeMap[pathName] || 'general';
580
+ }
581
+
582
+ calculateIntegrationPriority(pathName) {
583
+ const priorityMap = {
584
+ 'src/': 9,
585
+ 'app/': 8,
586
+ 'lib/': 7,
587
+ 'services/': 6,
588
+ 'components/': 5,
589
+ 'routes/': 4,
590
+ 'pages/': 3,
591
+ 'middleware/': 2
592
+ };
593
+
594
+ return priorityMap[pathName] || 1;
595
+ }
596
+ }
597
+
598
+ // CLI interface functions
599
+ export async function createMission(objective, options = {}) {
600
+ const missionSystem = new MissionSystem();
601
+ return await missionSystem.createMission(objective, options);
602
+ }
603
+
604
+ export async function listMissions() {
605
+ const missionSystem = new MissionSystem();
606
+ return await missionSystem.listMissions();
607
+ }
608
+
609
+ export async function getMission(missionId) {
610
+ const missionSystem = new MissionSystem();
611
+ return await missionSystem.getMission(missionId);
612
+ }