oneie 1.2.1 → 1.2.3

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,478 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Story Management System
5
+ * Manages stories within missions and orchestrates task creation
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 StorySystem {
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 createStory(missionId, objective, options = {}) {
24
+ console.log(chalk.blue('\nšŸ“š Creating new story...'));
25
+
26
+ // Step 1: Validate mission exists
27
+ const mission = await this.getMission(missionId);
28
+ if (!mission) {
29
+ throw new Error(`Mission not found: ${missionId}`);
30
+ }
31
+
32
+ // Step 2: Generate story template
33
+ const storyTemplate = await this.generateStoryTemplate(objective, mission);
34
+
35
+ // Step 3: Human-AI collaboration on story design
36
+ const story = await this.collaborativelyDesignStory(storyTemplate, options);
37
+
38
+ // Step 4: Create story file and initialize tasks
39
+ await this.initializeStory(missionId, story);
40
+
41
+ // Step 5: Generate initial tasks
42
+ await this.generateInitialTasks(story);
43
+
44
+ console.log(chalk.green(`\nāœ… Story "${story.name}" created successfully!`));
45
+ console.log(chalk.cyan(`šŸ“ Story location: .one/missions/${missionId}/stories/${story.id}.yaml`));
46
+
47
+ return story;
48
+ }
49
+
50
+ async generateStoryTemplate(objective, mission) {
51
+ console.log(chalk.gray('🧠 Generating story template...'));
52
+
53
+ const template = {
54
+ name: this.generateStoryName(objective),
55
+ id: this.generateStoryId(objective),
56
+ objective: objective,
57
+ missionId: mission.id,
58
+ suggestedTasks: this.suggestTasks(objective, mission),
59
+ suggestedAgents: this.suggestStoryAgents(objective, mission),
60
+ estimatedDuration: this.estimateStoryDuration(objective, mission),
61
+ priority: this.assessStoryPriority(objective, mission),
62
+ dependencies: this.identifyStoryDependencies(objective, mission)
63
+ };
64
+
65
+ return template;
66
+ }
67
+
68
+ generateStoryName(objective) {
69
+ return objective
70
+ .toLowerCase()
71
+ .replace(/[^a-z0-9\s]/g, '')
72
+ .replace(/\s+/g, '-')
73
+ .substring(0, 40);
74
+ }
75
+
76
+ generateStoryId(objective) {
77
+ const hash = this.hashString(objective).substring(0, 8);
78
+ return `story-${hash}`;
79
+ }
80
+
81
+ hashString(str) {
82
+ let hash = 0;
83
+ for (let i = 0; i < str.length; i++) {
84
+ const char = str.charCodeAt(i);
85
+ hash = ((hash << 5) - hash) + char;
86
+ hash = hash & hash;
87
+ }
88
+ return Math.abs(hash).toString(16);
89
+ }
90
+
91
+ suggestTasks(objective, mission) {
92
+ const tasks = [];
93
+ const objectiveLower = objective.toLowerCase();
94
+
95
+ // Task patterns based on objective type
96
+ if (objectiveLower.includes('implement') || objectiveLower.includes('build') || objectiveLower.includes('create')) {
97
+ tasks.push('planning', 'design', 'implementation', 'testing', 'documentation');
98
+ } else if (objectiveLower.includes('fix') || objectiveLower.includes('debug') || objectiveLower.includes('resolve')) {
99
+ tasks.push('investigation', 'diagnosis', 'solution-design', 'implementation', 'verification');
100
+ } else if (objectiveLower.includes('optimize') || objectiveLower.includes('improve') || objectiveLower.includes('enhance')) {
101
+ tasks.push('analysis', 'benchmarking', 'optimization', 'testing', 'validation');
102
+ } else if (objectiveLower.includes('deploy') || objectiveLower.includes('release') || objectiveLower.includes('launch')) {
103
+ tasks.push('preparation', 'deployment', 'monitoring', 'verification', 'rollback-plan');
104
+ } else {
105
+ // Default task pattern
106
+ tasks.push('research', 'planning', 'execution', 'review');
107
+ }
108
+
109
+ // Add tech-specific tasks based on mission architecture
110
+ if (mission.architecture?.techStack?.frameworks?.includes('React')) {
111
+ if (objectiveLower.includes('component') || objectiveLower.includes('ui')) {
112
+ tasks.push('component-design', 'styling', 'state-management');
113
+ }
114
+ }
115
+
116
+ if (mission.architecture?.techStack?.frameworks?.includes('Express')) {
117
+ if (objectiveLower.includes('api') || objectiveLower.includes('endpoint')) {
118
+ tasks.push('route-definition', 'middleware', 'error-handling');
119
+ }
120
+ }
121
+
122
+ return tasks;
123
+ }
124
+
125
+ suggestStoryAgents(objective, mission) {
126
+ const agents = new Set();
127
+ const objectiveLower = objective.toLowerCase();
128
+
129
+ // Always include story coordination agents
130
+ agents.add('Story Teller');
131
+ agents.add('Task Master');
132
+
133
+ // Add mission agents that are relevant to this story
134
+ const relevantMissionAgents = mission.agents.filter(agent => {
135
+ const agentLower = agent.toLowerCase();
136
+
137
+ // Frontend-related objectives
138
+ if (objectiveLower.includes('ui') || objectiveLower.includes('component') || objectiveLower.includes('frontend')) {
139
+ return agentLower.includes('react') || agentLower.includes('frontend') || agentLower.includes('ui');
140
+ }
141
+
142
+ // Backend-related objectives
143
+ if (objectiveLower.includes('api') || objectiveLower.includes('server') || objectiveLower.includes('backend')) {
144
+ return agentLower.includes('backend') || agentLower.includes('api') || agentLower.includes('server');
145
+ }
146
+
147
+ // Database-related objectives
148
+ if (objectiveLower.includes('database') || objectiveLower.includes('data') || objectiveLower.includes('storage')) {
149
+ return agentLower.includes('database') || agentLower.includes('data');
150
+ }
151
+
152
+ // Testing-related objectives
153
+ if (objectiveLower.includes('test') || objectiveLower.includes('quality')) {
154
+ return agentLower.includes('test') || agentLower.includes('quality') || agentLower.includes('qa');
155
+ }
156
+
157
+ // Include general development agents
158
+ return agentLower.includes('developer') || agentLower.includes('specialist');
159
+ });
160
+
161
+ relevantMissionAgents.forEach(agent => agents.add(agent));
162
+
163
+ // If no specific agents matched, include some general ones from mission
164
+ if (agents.size <= 2) {
165
+ mission.agents.slice(0, 2).forEach(agent => agents.add(agent));
166
+ }
167
+
168
+ return Array.from(agents);
169
+ }
170
+
171
+ estimateStoryDuration(objective, mission) {
172
+ let baseDays = 3; // Default story duration
173
+
174
+ const objectiveLower = objective.toLowerCase();
175
+ const complexityKeywords = ['complex', 'integration', 'migration', 'refactor', 'architecture'];
176
+ const simpleKeywords = ['fix', 'update', 'small', 'minor', 'simple'];
177
+
178
+ // Adjust based on objective complexity
179
+ if (complexityKeywords.some(keyword => objectiveLower.includes(keyword))) {
180
+ baseDays += 3;
181
+ } else if (simpleKeywords.some(keyword => objectiveLower.includes(keyword))) {
182
+ baseDays -= 1;
183
+ }
184
+
185
+ // Adjust based on mission complexity
186
+ if (mission.complexity === 'high') {
187
+ baseDays += 2;
188
+ } else if (mission.complexity === 'low') {
189
+ baseDays -= 1;
190
+ }
191
+
192
+ baseDays = Math.max(1, baseDays); // Minimum 1 day
193
+
194
+ return baseDays <= 3 ? `${baseDays} days` : `${Math.ceil(baseDays/5)} week${baseDays > 5 ? 's' : ''}`;
195
+ }
196
+
197
+ assessStoryPriority(objective, mission) {
198
+ const objectiveLower = objective.toLowerCase();
199
+
200
+ // High priority indicators
201
+ const highPriorityKeywords = ['critical', 'urgent', 'blocker', 'security', 'bug', 'fix'];
202
+ if (highPriorityKeywords.some(keyword => objectiveLower.includes(keyword))) {
203
+ return 'high';
204
+ }
205
+
206
+ // Low priority indicators
207
+ const lowPriorityKeywords = ['nice-to-have', 'enhancement', 'optional', 'future'];
208
+ if (lowPriorityKeywords.some(keyword => objectiveLower.includes(keyword))) {
209
+ return 'low';
210
+ }
211
+
212
+ return 'medium';
213
+ }
214
+
215
+ identifyStoryDependencies(objective, mission) {
216
+ // For now, return empty dependencies. In future versions, this could analyze
217
+ // existing stories and identify dependencies based on objective content
218
+ return [];
219
+ }
220
+
221
+ async collaborativelyDesignStory(template, options) {
222
+ console.log(chalk.blue('\nšŸ¤ Collaborative story design...'));
223
+
224
+ // Show AI analysis
225
+ console.log(chalk.cyan('\nšŸ¤– AI Analysis:'));
226
+ console.log(` Suggested name: ${template.name}`);
227
+ console.log(` Estimated duration: ${template.estimatedDuration}`);
228
+ console.log(` Priority: ${template.priority}`);
229
+ console.log(` Suggested agents: ${template.suggestedAgents.join(', ')}`);
230
+ console.log(` Suggested tasks: ${template.suggestedTasks.join(', ')}`);
231
+
232
+ if (options.interactive !== false) {
233
+ // Get human input
234
+ const answers = await inquirer.prompt([
235
+ {
236
+ type: 'input',
237
+ name: 'name',
238
+ message: 'Story name:',
239
+ default: template.name
240
+ },
241
+ {
242
+ type: 'editor',
243
+ name: 'description',
244
+ message: 'Story description:',
245
+ default: `# ${template.objective}\n\n[Describe what this story will accomplish and how it contributes to the mission]`
246
+ },
247
+ {
248
+ type: 'checkbox',
249
+ name: 'agents',
250
+ message: 'Select agents for this story:',
251
+ choices: template.suggestedAgents,
252
+ default: template.suggestedAgents.slice(0, 3)
253
+ },
254
+ {
255
+ type: 'list',
256
+ name: 'priority',
257
+ message: 'Story priority:',
258
+ choices: ['high', 'medium', 'low'],
259
+ default: template.priority
260
+ },
261
+ {
262
+ type: 'input',
263
+ name: 'duration',
264
+ message: 'Expected duration:',
265
+ default: template.estimatedDuration
266
+ }
267
+ ]);
268
+
269
+ // Merge human input with AI suggestions
270
+ Object.assign(template, answers);
271
+ template.tasks = template.suggestedTasks; // Keep AI task suggestions
272
+ } else {
273
+ // Non-interactive mode
274
+ template.agents = template.suggestedAgents.slice(0, 3);
275
+ template.tasks = template.suggestedTasks;
276
+ template.duration = template.estimatedDuration;
277
+ template.description = `# ${template.objective}\n\nAI-generated story to ${template.objective.toLowerCase()}.`;
278
+ }
279
+
280
+ console.log(chalk.green('āœ… Story design complete'));
281
+ return template;
282
+ }
283
+
284
+ async initializeStory(missionId, story) {
285
+ console.log(chalk.gray('šŸ“ Creating story structure...'));
286
+
287
+ const missionDir = path.join(this.missionsDir, missionId);
288
+ const storiesDir = path.join(missionDir, 'stories');
289
+
290
+ // Ensure stories directory exists
291
+ await fs.ensureDir(storiesDir);
292
+
293
+ // Create story data
294
+ const storyData = {
295
+ name: story.name,
296
+ id: story.id,
297
+ missionId: missionId,
298
+ objective: story.objective,
299
+ description: story.description,
300
+ status: 'planning',
301
+ priority: story.priority,
302
+ created: new Date().toISOString(),
303
+ agents: story.agents,
304
+ tasks: story.tasks.map(taskName => ({
305
+ name: taskName,
306
+ id: `task-${this.hashString(taskName).substring(0, 8)}`,
307
+ status: 'pending',
308
+ created: new Date().toISOString()
309
+ })),
310
+ duration: story.duration,
311
+ dependencies: story.dependencies || []
312
+ };
313
+
314
+ // Save story file
315
+ await fs.writeFile(
316
+ path.join(storiesDir, `${story.id}.yaml`),
317
+ yaml.dump(storyData, { indent: 2 })
318
+ );
319
+
320
+ // Create story README
321
+ const readmeContent = `# ${story.name}
322
+
323
+ ${story.description || `Story: ${story.objective}`}
324
+
325
+ ## Objective
326
+ ${story.objective}
327
+
328
+ ## Agents
329
+ ${story.agents.map(agent => `- ${agent}`).join('\n')}
330
+
331
+ ## Tasks
332
+ ${storyData.tasks.map(task => `- [ ] ${task.name} (${task.status})`).join('\n')}
333
+
334
+ ## Details
335
+ - Priority: ${story.priority}
336
+ - Duration: ${story.duration}
337
+ - Status: ${storyData.status}
338
+ - Created: ${storyData.created}
339
+
340
+ ## Dependencies
341
+ ${story.dependencies.length > 0 ? story.dependencies.map(dep => `- ${dep}`).join('\n') : 'None'}
342
+ `;
343
+
344
+ await fs.writeFile(path.join(storiesDir, `${story.id}.md`), readmeContent);
345
+
346
+ story.tasks = storyData.tasks; // Update with full task objects
347
+ return story;
348
+ }
349
+
350
+ async generateInitialTasks(story) {
351
+ console.log(chalk.gray('šŸ“‹ Generating initial tasks...'));
352
+
353
+ // Tasks are already created in initializeStory
354
+ // This method could be extended to create more detailed task specifications
355
+ console.log(chalk.green(`āœ… Generated ${story.tasks.length} tasks`));
356
+ }
357
+
358
+ async listStories(missionId = null) {
359
+ const stories = [];
360
+
361
+ if (missionId) {
362
+ // List stories for a specific mission
363
+ const missionDir = path.join(this.missionsDir, missionId);
364
+ const storiesDir = path.join(missionDir, 'stories');
365
+
366
+ if (await fs.pathExists(storiesDir)) {
367
+ const storyFiles = await fs.readdir(storiesDir);
368
+
369
+ for (const file of storyFiles) {
370
+ if (file.endsWith('.yaml')) {
371
+ const storyPath = path.join(storiesDir, file);
372
+ const storyData = yaml.load(await fs.readFile(storyPath, 'utf8'));
373
+ stories.push(storyData);
374
+ }
375
+ }
376
+ }
377
+ } else {
378
+ // List all stories across all missions
379
+ if (await fs.pathExists(this.missionsDir)) {
380
+ const missionDirs = await fs.readdir(this.missionsDir);
381
+
382
+ for (const missionDir of missionDirs) {
383
+ const storiesDir = path.join(this.missionsDir, missionDir, 'stories');
384
+
385
+ if (await fs.pathExists(storiesDir)) {
386
+ const storyFiles = await fs.readdir(storiesDir);
387
+
388
+ for (const file of storyFiles) {
389
+ if (file.endsWith('.yaml')) {
390
+ const storyPath = path.join(storiesDir, file);
391
+ const storyData = yaml.load(await fs.readFile(storyPath, 'utf8'));
392
+ stories.push(storyData);
393
+ }
394
+ }
395
+ }
396
+ }
397
+ }
398
+ }
399
+
400
+ return stories.sort((a, b) => new Date(b.created) - new Date(a.created));
401
+ }
402
+
403
+ async getStory(storyId, missionId = null) {
404
+ if (missionId) {
405
+ // Look in specific mission
406
+ const storyPath = path.join(this.missionsDir, missionId, 'stories', `${storyId}.yaml`);
407
+ if (await fs.pathExists(storyPath)) {
408
+ return yaml.load(await fs.readFile(storyPath, 'utf8'));
409
+ }
410
+ } else {
411
+ // Search across all missions
412
+ const stories = await this.listStories();
413
+ return stories.find(story => story.id === storyId);
414
+ }
415
+
416
+ return null;
417
+ }
418
+
419
+ async updateStoryStatus(storyId, status, missionId = null) {
420
+ const story = await this.getStory(storyId, missionId);
421
+ if (!story) {
422
+ throw new Error(`Story not found: ${storyId}`);
423
+ }
424
+
425
+ story.status = status;
426
+ story.updated = new Date().toISOString();
427
+
428
+ // Find and update the story file
429
+ const storyPath = missionId
430
+ ? path.join(this.missionsDir, missionId, 'stories', `${storyId}.yaml`)
431
+ : await this.findStoryPath(storyId);
432
+
433
+ if (storyPath && await fs.pathExists(storyPath)) {
434
+ await fs.writeFile(storyPath, yaml.dump(story, { indent: 2 }));
435
+ return story;
436
+ }
437
+
438
+ throw new Error(`Could not update story file: ${storyId}`);
439
+ }
440
+
441
+ async findStoryPath(storyId) {
442
+ const stories = await this.listStories();
443
+ const story = stories.find(s => s.id === storyId);
444
+ if (story) {
445
+ return path.join(this.missionsDir, story.missionId, 'stories', `${storyId}.yaml`);
446
+ }
447
+ return null;
448
+ }
449
+
450
+ async getMission(missionId) {
451
+ const missionFile = path.join(this.missionsDir, missionId, 'mission.yaml');
452
+ if (await fs.pathExists(missionFile)) {
453
+ return yaml.load(await fs.readFile(missionFile, 'utf8'));
454
+ }
455
+ return null;
456
+ }
457
+ }
458
+
459
+ // CLI interface functions
460
+ export async function createStory(missionId, objective, options = {}) {
461
+ const storySystem = new StorySystem();
462
+ return await storySystem.createStory(missionId, objective, options);
463
+ }
464
+
465
+ export async function listStories(missionId = null) {
466
+ const storySystem = new StorySystem();
467
+ return await storySystem.listStories(missionId);
468
+ }
469
+
470
+ export async function getStory(storyId, missionId = null) {
471
+ const storySystem = new StorySystem();
472
+ return await storySystem.getStory(storyId, missionId);
473
+ }
474
+
475
+ export async function updateStoryStatus(storyId, status, missionId = null) {
476
+ const storySystem = new StorySystem();
477
+ return await storySystem.updateStoryStatus(storyId, status, missionId);
478
+ }