gthinking 1.0.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 (53) hide show
  1. package/README.md +283 -0
  2. package/analysis.ts +986 -0
  3. package/creativity.ts +1002 -0
  4. package/dist/analysis.d.ts +52 -0
  5. package/dist/analysis.d.ts.map +1 -0
  6. package/dist/analysis.js +792 -0
  7. package/dist/analysis.js.map +1 -0
  8. package/dist/creativity.d.ts +80 -0
  9. package/dist/creativity.d.ts.map +1 -0
  10. package/dist/creativity.js +778 -0
  11. package/dist/creativity.js.map +1 -0
  12. package/dist/engine.d.ts +76 -0
  13. package/dist/engine.d.ts.map +1 -0
  14. package/dist/engine.js +675 -0
  15. package/dist/engine.js.map +1 -0
  16. package/dist/examples.d.ts +7 -0
  17. package/dist/examples.d.ts.map +1 -0
  18. package/dist/examples.js +506 -0
  19. package/dist/examples.js.map +1 -0
  20. package/dist/index.d.ts +38 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +126 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/learning.d.ts +72 -0
  25. package/dist/learning.d.ts.map +1 -0
  26. package/dist/learning.js +615 -0
  27. package/dist/learning.js.map +1 -0
  28. package/dist/planning.d.ts +58 -0
  29. package/dist/planning.d.ts.map +1 -0
  30. package/dist/planning.js +824 -0
  31. package/dist/planning.js.map +1 -0
  32. package/dist/reasoning.d.ts +72 -0
  33. package/dist/reasoning.d.ts.map +1 -0
  34. package/dist/reasoning.js +792 -0
  35. package/dist/reasoning.js.map +1 -0
  36. package/dist/search-discovery.d.ts +73 -0
  37. package/dist/search-discovery.d.ts.map +1 -0
  38. package/dist/search-discovery.js +505 -0
  39. package/dist/search-discovery.js.map +1 -0
  40. package/dist/types.d.ts +535 -0
  41. package/dist/types.d.ts.map +1 -0
  42. package/dist/types.js +77 -0
  43. package/dist/types.js.map +1 -0
  44. package/engine.ts +928 -0
  45. package/examples.ts +717 -0
  46. package/index.ts +106 -0
  47. package/learning.ts +779 -0
  48. package/package.json +51 -0
  49. package/planning.ts +1028 -0
  50. package/reasoning.ts +1019 -0
  51. package/search-discovery.ts +654 -0
  52. package/tsconfig.json +25 -0
  53. package/types.ts +674 -0
@@ -0,0 +1,824 @@
1
+ "use strict";
2
+ /**
3
+ * Planning Module
4
+ * Task decomposition, prioritization, resource allocation, and progress tracking
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.planningEngine = exports.PlanningEngine = void 0;
8
+ const types_1 = require("./types");
9
+ const events_1 = require("events");
10
+ class TaskDecompositionEngine {
11
+ constructor() {
12
+ this.decompositionRules = [
13
+ {
14
+ pattern: /build|create|develop|implement/i,
15
+ subtasks: [
16
+ 'Research and requirements gathering',
17
+ 'Design and architecture',
18
+ 'Implementation',
19
+ 'Testing and validation',
20
+ 'Deployment'
21
+ ],
22
+ dependencies: [[], ['0'], ['1'], ['2'], ['3']]
23
+ },
24
+ {
25
+ pattern: /analyze|research|investigate/i,
26
+ subtasks: [
27
+ 'Define scope and objectives',
28
+ 'Gather existing data',
29
+ 'Conduct analysis',
30
+ 'Document findings',
31
+ 'Present recommendations'
32
+ ],
33
+ dependencies: [[], ['0'], ['1'], ['2'], ['3']]
34
+ },
35
+ {
36
+ pattern: /optimize|improve|enhance/i,
37
+ subtasks: [
38
+ 'Current state assessment',
39
+ 'Identify improvement areas',
40
+ 'Design improvements',
41
+ 'Implement changes',
42
+ 'Measure results'
43
+ ],
44
+ dependencies: [[], ['0'], ['1'], ['2'], ['3']]
45
+ }
46
+ ];
47
+ }
48
+ decompose(goal) {
49
+ // Find matching decomposition rule
50
+ for (const rule of this.decompositionRules) {
51
+ if (rule.pattern.test(goal)) {
52
+ return {
53
+ subtasks: rule.subtasks,
54
+ dependencies: rule.dependencies
55
+ };
56
+ }
57
+ }
58
+ // Default decomposition
59
+ return {
60
+ subtasks: [
61
+ 'Understand requirements',
62
+ 'Plan approach',
63
+ 'Execute plan',
64
+ 'Review and validate'
65
+ ],
66
+ dependencies: [[], ['0'], ['1'], ['2']]
67
+ };
68
+ }
69
+ estimateComplexity(task) {
70
+ // Estimate complexity based on keywords
71
+ const complexityIndicators = [
72
+ { keywords: ['complex', 'difficult', 'challenging', 'advanced'], weight: 0.9 },
73
+ { keywords: ['simple', 'easy', 'basic', 'straightforward'], weight: 0.3 },
74
+ { keywords: ['research', 'analysis', 'investigation'], weight: 0.7 },
75
+ { keywords: ['implement', 'build', 'develop'], weight: 0.8 }
76
+ ];
77
+ const taskLower = task.toLowerCase();
78
+ let complexity = 0.5; // Default
79
+ complexityIndicators.forEach(indicator => {
80
+ if (indicator.keywords.some(kw => taskLower.includes(kw))) {
81
+ complexity = indicator.weight;
82
+ }
83
+ });
84
+ // Adjust based on task length (longer tasks tend to be more complex)
85
+ const wordCount = task.split(/\s+/).length;
86
+ complexity += Math.min(0.2, wordCount * 0.01);
87
+ return Math.min(1, complexity);
88
+ }
89
+ estimateDuration(task, complexity) {
90
+ // Duration in minutes
91
+ const baseDuration = 30;
92
+ const complexityMultiplier = 1 + complexity * 4; // 1x to 5x
93
+ return Math.round(baseDuration * complexityMultiplier);
94
+ }
95
+ }
96
+ class PrioritizationEngine {
97
+ constructor() {
98
+ this.weights = {
99
+ urgency: 0.25,
100
+ importance: 0.3,
101
+ effort: 0.2,
102
+ risk: 0.15,
103
+ dependencies: 0.1
104
+ };
105
+ }
106
+ prioritize(tasks) {
107
+ const scoredTasks = tasks.map(task => ({
108
+ task,
109
+ score: this.calculatePriorityScore(task)
110
+ }));
111
+ return scoredTasks
112
+ .sort((a, b) => b.score - a.score)
113
+ .map(({ task }) => task);
114
+ }
115
+ calculatePriorityScore(task) {
116
+ const criteria = this.assessCriteria(task);
117
+ // Calculate weighted score
118
+ let score = 0;
119
+ score += criteria.urgency * this.weights.urgency;
120
+ score += criteria.importance * this.weights.importance;
121
+ score += (1 - criteria.effort) * this.weights.effort; // Lower effort = higher priority
122
+ score += (1 - criteria.risk) * this.weights.risk; // Lower risk = higher priority
123
+ score += (1 - criteria.dependencies) * this.weights.dependencies; // Fewer deps = higher priority
124
+ return score;
125
+ }
126
+ assessCriteria(task) {
127
+ return {
128
+ urgency: this.assessUrgency(task),
129
+ importance: this.assessImportance(task),
130
+ effort: this.assessEffort(task),
131
+ risk: this.assessRisk(task),
132
+ dependencies: this.assessDependencies(task)
133
+ };
134
+ }
135
+ assessUrgency(task) {
136
+ const urgencyKeywords = ['urgent', 'asap', 'immediate', 'critical', 'deadline'];
137
+ const taskText = `${task.title} ${task.description}`.toLowerCase();
138
+ if (task.priority === types_1.Priority.CRITICAL)
139
+ return 1;
140
+ if (task.priority === types_1.Priority.HIGH)
141
+ return 0.8;
142
+ const matches = urgencyKeywords.filter(kw => taskText.includes(kw)).length;
143
+ return Math.min(1, matches * 0.3 + (task.priority === types_1.Priority.MEDIUM ? 0.3 : task.priority === types_1.Priority.LOW ? 0.2 : 0.1));
144
+ }
145
+ assessImportance(task) {
146
+ const importanceKeywords = ['essential', 'crucial', 'key', 'important', 'core'];
147
+ const taskText = `${task.title} ${task.description}`.toLowerCase();
148
+ if (task.tags.includes('critical'))
149
+ return 1;
150
+ const matches = importanceKeywords.filter(kw => taskText.includes(kw)).length;
151
+ return Math.min(1, matches * 0.25 + 0.3);
152
+ }
153
+ assessEffort(task) {
154
+ // Normalize estimated duration (assuming max 8 hours)
155
+ return Math.min(1, task.estimatedDuration / 480);
156
+ }
157
+ assessRisk(task) {
158
+ const riskKeywords = ['risk', 'uncertain', 'unknown', 'complex', 'difficult'];
159
+ const taskText = `${task.title} ${task.description}`.toLowerCase();
160
+ const matches = riskKeywords.filter(kw => taskText.includes(kw)).length;
161
+ return Math.min(1, matches * 0.3);
162
+ }
163
+ assessDependencies(task) {
164
+ return Math.min(1, task.dependencies.length / 5);
165
+ }
166
+ /**
167
+ * Calculate critical path
168
+ */
169
+ calculateCriticalPath(tasks) {
170
+ const taskMap = new Map(tasks.map(t => [t.id, t]));
171
+ const visited = new Set();
172
+ const path = [];
173
+ const visit = (taskId, currentPath = []) => {
174
+ if (visited.has(taskId))
175
+ return 0;
176
+ if (currentPath.includes(taskId))
177
+ return 0; // Cycle detected
178
+ const task = taskMap.get(taskId);
179
+ if (!task)
180
+ return 0;
181
+ let maxPathDuration = task.estimatedDuration;
182
+ for (const depId of task.dependencies) {
183
+ const depDuration = visit(depId, [...currentPath, taskId]);
184
+ maxPathDuration = Math.max(maxPathDuration, task.estimatedDuration + depDuration);
185
+ }
186
+ visited.add(taskId);
187
+ path.push(taskId);
188
+ return maxPathDuration;
189
+ };
190
+ // Find the longest path
191
+ let maxDuration = 0;
192
+ let criticalPath = [];
193
+ for (const task of tasks) {
194
+ visited.clear();
195
+ path.length = 0;
196
+ const duration = visit(task.id);
197
+ if (duration > maxDuration) {
198
+ maxDuration = duration;
199
+ criticalPath = [...path];
200
+ }
201
+ }
202
+ return criticalPath;
203
+ }
204
+ }
205
+ // ============================================================================
206
+ // RESOURCE ALLOCATOR
207
+ // ============================================================================
208
+ class ResourceAllocator {
209
+ constructor() {
210
+ this.resources = new Map();
211
+ }
212
+ addResource(resource) {
213
+ this.resources.set(resource.id, resource);
214
+ }
215
+ allocate(tasks) {
216
+ const allocation = new Map();
217
+ const resourceAvailability = new Map();
218
+ // Initialize availability
219
+ this.resources.forEach((resource, id) => {
220
+ resourceAvailability.set(id, resource.availability);
221
+ });
222
+ // Allocate resources to tasks
223
+ for (const task of tasks) {
224
+ const suitableResources = this.findSuitableResources(task);
225
+ const allocated = [];
226
+ for (const resource of suitableResources) {
227
+ const available = resourceAvailability.get(resource.id) || 0;
228
+ if (available > 0) {
229
+ allocated.push(resource.id);
230
+ resourceAvailability.set(resource.id, available - 1);
231
+ }
232
+ }
233
+ allocation.set(task.id, allocated);
234
+ }
235
+ return allocation;
236
+ }
237
+ findSuitableResources(task) {
238
+ return Array.from(this.resources.values())
239
+ .filter(resource => {
240
+ // Check if resource skills match task requirements
241
+ if (task.tags.length > 0 && resource.skills) {
242
+ return task.tags.some(tag => resource.skills.some(skill => skill.toLowerCase().includes(tag.toLowerCase()) ||
243
+ tag.toLowerCase().includes(skill.toLowerCase())));
244
+ }
245
+ return true;
246
+ })
247
+ .sort((a, b) => b.availability - a.availability);
248
+ }
249
+ checkOverallocation() {
250
+ const overallocations = [];
251
+ this.resources.forEach((resource, id) => {
252
+ if (resource.availability < 0) {
253
+ overallocations.push({
254
+ resourceId: id,
255
+ overallocation: Math.abs(resource.availability)
256
+ });
257
+ }
258
+ });
259
+ return overallocations;
260
+ }
261
+ getResourceUtilization() {
262
+ const utilization = new Map();
263
+ this.resources.forEach((resource, id) => {
264
+ // Calculate utilization (simplified)
265
+ utilization.set(id, 1 - resource.availability);
266
+ });
267
+ return utilization;
268
+ }
269
+ }
270
+ // ============================================================================
271
+ // PROGRESS TRACKER
272
+ // ============================================================================
273
+ class ProgressTracker {
274
+ constructor() {
275
+ this.taskHistory = new Map();
276
+ }
277
+ recordProgress(taskId, status, progress) {
278
+ if (!this.taskHistory.has(taskId)) {
279
+ this.taskHistory.set(taskId, []);
280
+ }
281
+ this.taskHistory.get(taskId).push({
282
+ timestamp: new Date(),
283
+ status,
284
+ progress: Math.min(100, Math.max(0, progress))
285
+ });
286
+ }
287
+ getProgress(taskId) {
288
+ const history = this.taskHistory.get(taskId);
289
+ if (!history || history.length === 0)
290
+ return 0;
291
+ return history[history.length - 1].progress;
292
+ }
293
+ calculateVelocity(taskId) {
294
+ const history = this.taskHistory.get(taskId);
295
+ if (!history || history.length < 2)
296
+ return 0;
297
+ const first = history[0];
298
+ const last = history[history.length - 1];
299
+ const timeDiff = last.timestamp.getTime() - first.timestamp.getTime();
300
+ const progressDiff = last.progress - first.progress;
301
+ return timeDiff > 0 ? (progressDiff / timeDiff) * 3600000 : 0; // Progress per hour
302
+ }
303
+ predictCompletion(taskId, totalWork) {
304
+ const velocity = this.calculateVelocity(taskId);
305
+ const currentProgress = this.getProgress(taskId);
306
+ if (velocity <= 0 || currentProgress >= 100)
307
+ return null;
308
+ const remainingWork = totalWork * (1 - currentProgress / 100);
309
+ const hoursRemaining = remainingWork / velocity;
310
+ return new Date(Date.now() + hoursRemaining * 3600000);
311
+ }
312
+ getProgressTrend(taskId) {
313
+ const history = this.taskHistory.get(taskId);
314
+ if (!history || history.length < 3)
315
+ return 'stable';
316
+ const recent = history.slice(-3);
317
+ const velocities = [];
318
+ for (let i = 1; i < recent.length; i++) {
319
+ const timeDiff = recent[i].timestamp.getTime() - recent[i - 1].timestamp.getTime();
320
+ const progressDiff = recent[i].progress - recent[i - 1].progress;
321
+ velocities.push(timeDiff > 0 ? progressDiff / timeDiff : 0);
322
+ }
323
+ const avgVelocity = velocities.reduce((a, b) => a + b, 0) / velocities.length;
324
+ const firstVelocity = velocities[0];
325
+ if (avgVelocity > firstVelocity * 1.2)
326
+ return 'improving';
327
+ if (avgVelocity < firstVelocity * 0.8)
328
+ return 'declining';
329
+ return 'stable';
330
+ }
331
+ }
332
+ // ============================================================================
333
+ // RISK ANALYZER
334
+ // ============================================================================
335
+ class RiskAnalyzer {
336
+ constructor() {
337
+ this.knownRisks = new Map();
338
+ }
339
+ analyzeRisks(tasks, resources) {
340
+ const risks = [];
341
+ // Analyze task-related risks
342
+ tasks.forEach(task => {
343
+ const taskRisks = this.identifyTaskRisks(task);
344
+ risks.push(...taskRisks);
345
+ });
346
+ // Analyze resource-related risks
347
+ const resourceRisks = this.identifyResourceRisks(tasks, resources);
348
+ risks.push(...resourceRisks);
349
+ // Analyze schedule-related risks
350
+ const scheduleRisks = this.identifyScheduleRisks(tasks);
351
+ risks.push(...scheduleRisks);
352
+ // Sort by risk score (probability * impact)
353
+ return risks
354
+ .map(risk => ({ ...risk, riskScore: risk.probability * risk.impact }))
355
+ .sort((a, b) => b.riskScore - a.riskScore);
356
+ }
357
+ identifyTaskRisks(task) {
358
+ const risks = [];
359
+ // Complexity risk
360
+ if (task.estimatedDuration > 240) { // > 4 hours
361
+ risks.push({
362
+ id: `risk_complexity_${task.id}`,
363
+ description: `Task "${task.title}" is complex and may take longer than estimated`,
364
+ probability: 0.6,
365
+ impact: 0.7,
366
+ mitigation: 'Break down into smaller subtasks',
367
+ status: 'identified'
368
+ });
369
+ }
370
+ // Dependency risk
371
+ if (task.dependencies.length > 3) {
372
+ risks.push({
373
+ id: `risk_deps_${task.id}`,
374
+ description: `Task "${task.title}" has many dependencies`,
375
+ probability: 0.5,
376
+ impact: 0.6,
377
+ mitigation: 'Monitor dependencies closely and have backup plans',
378
+ status: 'identified'
379
+ });
380
+ }
381
+ // Uncertainty risk
382
+ const uncertaintyKeywords = ['unclear', 'unknown', 'uncertain', 'tbd', 'tba'];
383
+ const taskText = `${task.title} ${task.description}`.toLowerCase();
384
+ if (uncertaintyKeywords.some(kw => taskText.includes(kw))) {
385
+ risks.push({
386
+ id: `risk_uncertainty_${task.id}`,
387
+ description: `Task "${task.title}" has unclear requirements`,
388
+ probability: 0.7,
389
+ impact: 0.5,
390
+ mitigation: 'Clarify requirements before starting',
391
+ status: 'identified'
392
+ });
393
+ }
394
+ return risks;
395
+ }
396
+ identifyResourceRisks(tasks, resources) {
397
+ const risks = [];
398
+ // Resource availability risk
399
+ const totalAvailability = resources.reduce((sum, r) => sum + r.availability, 0);
400
+ const totalWork = tasks.reduce((sum, t) => sum + t.estimatedDuration, 0);
401
+ if (totalWork > totalAvailability * 480) { // Assuming 8 hours per availability unit
402
+ risks.push({
403
+ id: 'risk_resource_availability',
404
+ description: 'Insufficient resources for planned work',
405
+ probability: 0.8,
406
+ impact: 0.9,
407
+ mitigation: 'Add more resources or extend timeline',
408
+ status: 'identified'
409
+ });
410
+ }
411
+ return risks;
412
+ }
413
+ identifyScheduleRisks(tasks) {
414
+ const risks = [];
415
+ // Check for tight schedules
416
+ const criticalTasks = tasks.filter(t => t.priority === types_1.Priority.CRITICAL);
417
+ if (criticalTasks.length > tasks.length * 0.3) {
418
+ risks.push({
419
+ id: 'risk_tight_schedule',
420
+ description: 'Too many critical tasks may lead to schedule slip',
421
+ probability: 0.6,
422
+ impact: 0.7,
423
+ mitigation: 'Re-prioritize and stagger critical tasks',
424
+ status: 'identified'
425
+ });
426
+ }
427
+ return risks;
428
+ }
429
+ updateRiskStatus(riskId, status) {
430
+ const risk = this.knownRisks.get(riskId);
431
+ if (risk) {
432
+ risk.status = status;
433
+ }
434
+ }
435
+ }
436
+ // ============================================================================
437
+ // MAIN PLANNING ENGINE
438
+ // ============================================================================
439
+ class PlanningEngine extends events_1.EventEmitter {
440
+ constructor() {
441
+ super();
442
+ this.plans = new Map();
443
+ this.decompositionEngine = new TaskDecompositionEngine();
444
+ this.prioritizationEngine = new PrioritizationEngine();
445
+ this.resourceAllocator = new ResourceAllocator();
446
+ this.progressTracker = new ProgressTracker();
447
+ this.riskAnalyzer = new RiskAnalyzer();
448
+ }
449
+ /**
450
+ * Create a comprehensive plan
451
+ */
452
+ createPlan(goal, options = {}) {
453
+ const planId = this.generateId();
454
+ const createdAt = new Date();
455
+ this.emit('planning_start', {
456
+ id: planId,
457
+ stage: types_1.ThinkingStage.PLANNING,
458
+ timestamp: createdAt,
459
+ data: { goal }
460
+ });
461
+ // Decompose goal into tasks
462
+ const { subtasks, dependencies } = this.decompositionEngine.decompose(goal);
463
+ // Create tasks
464
+ const tasks = subtasks.map((description, index) => {
465
+ const complexity = this.decompositionEngine.estimateComplexity(description);
466
+ const duration = this.decompositionEngine.estimateDuration(description, complexity);
467
+ return {
468
+ id: `task_${planId}_${index}`,
469
+ title: description,
470
+ description,
471
+ priority: this.inferPriority(description, index),
472
+ status: types_1.TaskStatus.PENDING,
473
+ estimatedDuration: duration,
474
+ dependencies: dependencies[index].map(i => `task_${planId}_${i}`),
475
+ subtasks: [],
476
+ tags: []
477
+ };
478
+ });
479
+ // Prioritize tasks
480
+ const prioritizedTasks = this.prioritizationEngine.prioritize(tasks);
481
+ // Add resources if provided
482
+ if (options.resources) {
483
+ options.resources.forEach(r => this.resourceAllocator.addResource(r));
484
+ }
485
+ // Allocate resources
486
+ const resourceAllocation = this.resourceAllocator.allocate(prioritizedTasks);
487
+ // Assign resources to tasks
488
+ prioritizedTasks.forEach(task => {
489
+ const allocated = resourceAllocation.get(task.id) || [];
490
+ if (allocated.length > 0) {
491
+ task.assignedTo = allocated[0];
492
+ }
493
+ });
494
+ // Create milestones
495
+ const milestones = this.createMilestones(prioritizedTasks, goal);
496
+ // Create timeline
497
+ const timeline = this.createTimeline(prioritizedTasks, milestones, options.deadline);
498
+ // Analyze risks
499
+ const risks = this.riskAnalyzer.analyzeRisks(prioritizedTasks, options.resources || []);
500
+ const plan = {
501
+ id: planId,
502
+ goal,
503
+ tasks: prioritizedTasks,
504
+ milestones,
505
+ resources: options.resources || [],
506
+ timeline,
507
+ status: types_1.TaskStatus.PENDING,
508
+ createdAt,
509
+ updatedAt: createdAt
510
+ };
511
+ this.plans.set(planId, plan);
512
+ this.emit('planning_complete', {
513
+ id: planId,
514
+ stage: types_1.ThinkingStage.PLANNING,
515
+ timestamp: new Date(),
516
+ data: {
517
+ plan,
518
+ taskCount: tasks.length,
519
+ riskCount: risks.length
520
+ }
521
+ });
522
+ return plan;
523
+ }
524
+ /**
525
+ * Update task progress
526
+ */
527
+ updateTaskProgress(planId, taskId, progress, status) {
528
+ const plan = this.plans.get(planId);
529
+ if (!plan)
530
+ throw new Error(`Plan ${planId} not found`);
531
+ const task = plan.tasks.find(t => t.id === taskId);
532
+ if (!task)
533
+ throw new Error(`Task ${taskId} not found`);
534
+ const newStatus = status || (progress >= 100 ? types_1.TaskStatus.COMPLETED : progress > 0 ? types_1.TaskStatus.IN_PROGRESS : types_1.TaskStatus.PENDING);
535
+ task.status = newStatus;
536
+ if (newStatus === types_1.TaskStatus.COMPLETED) {
537
+ task.endTime = new Date();
538
+ }
539
+ else if (newStatus === types_1.TaskStatus.IN_PROGRESS && !task.startTime) {
540
+ task.startTime = new Date();
541
+ }
542
+ this.progressTracker.recordProgress(taskId, newStatus, progress);
543
+ // Update plan status
544
+ this.updatePlanStatus(plan);
545
+ plan.updatedAt = new Date();
546
+ this.emit('task_progress', {
547
+ id: taskId,
548
+ stage: types_1.ThinkingStage.PLANNING,
549
+ timestamp: new Date(),
550
+ data: { planId, taskId, progress, status: newStatus }
551
+ });
552
+ }
553
+ /**
554
+ * Generate progress report
555
+ */
556
+ generateProgressReport(planId) {
557
+ const plan = this.plans.get(planId);
558
+ if (!plan)
559
+ throw new Error(`Plan ${planId} not found`);
560
+ const completedTasks = plan.tasks.filter(t => t.status === types_1.TaskStatus.COMPLETED).length;
561
+ const totalTasks = plan.tasks.length;
562
+ const overallProgress = totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0;
563
+ // Calculate if on track
564
+ const onTrack = this.isOnTrack(plan);
565
+ // Get risks
566
+ const risks = this.riskAnalyzer.analyzeRisks(plan.tasks, plan.resources);
567
+ // Determine next actions
568
+ const nextActions = this.determineNextActions(plan);
569
+ return {
570
+ planId,
571
+ timestamp: new Date(),
572
+ overallProgress,
573
+ completedTasks,
574
+ totalTasks,
575
+ onTrack,
576
+ risks,
577
+ nextActions
578
+ };
579
+ }
580
+ /**
581
+ * Adjust plan based on changes
582
+ */
583
+ adjustPlan(planId, changes) {
584
+ const plan = this.plans.get(planId);
585
+ if (!plan)
586
+ throw new Error(`Plan ${planId} not found`);
587
+ // Add new tasks
588
+ if (changes.addTasks) {
589
+ const newTasks = changes.addTasks.map((task, index) => ({
590
+ ...task,
591
+ id: `task_${planId}_new_${Date.now()}_${index}`
592
+ }));
593
+ plan.tasks.push(...newTasks);
594
+ }
595
+ // Remove tasks
596
+ if (changes.removeTasks) {
597
+ plan.tasks = plan.tasks.filter(t => !changes.removeTasks.includes(t.id));
598
+ }
599
+ // Update tasks
600
+ if (changes.updateTasks) {
601
+ changes.updateTasks.forEach(update => {
602
+ const task = plan.tasks.find(t => t.id === update.id);
603
+ if (task) {
604
+ Object.assign(task, update);
605
+ }
606
+ });
607
+ }
608
+ // Re-prioritize
609
+ plan.tasks = this.prioritizationEngine.prioritize(plan.tasks);
610
+ // Update timeline if new deadline
611
+ if (changes.newDeadline) {
612
+ plan.timeline.endDate = changes.newDeadline;
613
+ }
614
+ plan.updatedAt = new Date();
615
+ this.emit('plan_adjusted', {
616
+ id: planId,
617
+ stage: types_1.ThinkingStage.PLANNING,
618
+ timestamp: new Date(),
619
+ data: { changes }
620
+ });
621
+ return plan;
622
+ }
623
+ /**
624
+ * Get plan by ID
625
+ */
626
+ getPlan(planId) {
627
+ return this.plans.get(planId);
628
+ }
629
+ /**
630
+ * Get all plans
631
+ */
632
+ getAllPlans() {
633
+ return Array.from(this.plans.values());
634
+ }
635
+ // Private helper methods
636
+ generateId() {
637
+ return `plan_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
638
+ }
639
+ inferPriority(description, index) {
640
+ const lower = description.toLowerCase();
641
+ if (lower.includes('critical') || lower.includes('urgent'))
642
+ return types_1.Priority.CRITICAL;
643
+ if (lower.includes('important') || lower.includes('key'))
644
+ return types_1.Priority.HIGH;
645
+ if (index < 2)
646
+ return types_1.Priority.HIGH; // First tasks are usually important
647
+ if (lower.includes('optional') || lower.includes('nice to have'))
648
+ return types_1.Priority.LOW;
649
+ return types_1.Priority.MEDIUM;
650
+ }
651
+ createMilestones(tasks, goal) {
652
+ const milestones = [];
653
+ const totalTasks = tasks.length;
654
+ if (totalTasks >= 3) {
655
+ milestones.push({
656
+ id: `milestone_${Date.now()}_1`,
657
+ title: 'Phase 1 Complete',
658
+ description: 'Initial phase completed',
659
+ criteria: [`Complete ${Math.ceil(totalTasks * 0.25)} tasks`],
660
+ status: types_1.TaskStatus.PENDING
661
+ });
662
+ }
663
+ if (totalTasks >= 5) {
664
+ milestones.push({
665
+ id: `milestone_${Date.now()}_2`,
666
+ title: 'Halfway Point',
667
+ description: '50% of tasks completed',
668
+ criteria: [`Complete ${Math.ceil(totalTasks * 0.5)} tasks`],
669
+ status: types_1.TaskStatus.PENDING
670
+ });
671
+ }
672
+ milestones.push({
673
+ id: `milestone_${Date.now()}_final`,
674
+ title: 'Goal Achieved',
675
+ description: goal,
676
+ criteria: ['All tasks completed'],
677
+ status: types_1.TaskStatus.PENDING
678
+ });
679
+ return milestones;
680
+ }
681
+ createTimeline(tasks, milestones, deadline) {
682
+ const startDate = new Date();
683
+ const criticalPath = this.prioritizationEngine.calculateCriticalPath(tasks);
684
+ // Calculate end date based on tasks
685
+ const totalDuration = tasks.reduce((sum, t) => sum + t.estimatedDuration, 0);
686
+ const calculatedEndDate = new Date(startDate.getTime() + totalDuration * 60000);
687
+ const endDate = deadline || calculatedEndDate;
688
+ // Create phases
689
+ const phases = this.createPhases(tasks);
690
+ return {
691
+ startDate,
692
+ endDate,
693
+ phases,
694
+ criticalPath,
695
+ buffer: deadline ?
696
+ (deadline.getTime() - calculatedEndDate.getTime()) / 60000 :
697
+ totalDuration * 0.2 // 20% buffer
698
+ };
699
+ }
700
+ createPhases(tasks) {
701
+ const phases = [];
702
+ const phaseNames = ['Planning', 'Execution', 'Review'];
703
+ const tasksPerPhase = Math.ceil(tasks.length / phaseNames.length);
704
+ let currentDate = new Date();
705
+ phaseNames.forEach((name, index) => {
706
+ const phaseTasks = tasks.slice(index * tasksPerPhase, (index + 1) * tasksPerPhase);
707
+ const phaseDuration = phaseTasks.reduce((sum, t) => sum + t.estimatedDuration, 0);
708
+ const phase = {
709
+ id: `phase_${Date.now()}_${index}`,
710
+ name,
711
+ startDate: new Date(currentDate),
712
+ endDate: new Date(currentDate.getTime() + phaseDuration * 60000),
713
+ tasks: phaseTasks.map(t => t.id),
714
+ dependencies: index > 0 ? [`phase_${Date.now()}_${index - 1}`] : []
715
+ };
716
+ phases.push(phase);
717
+ currentDate = phase.endDate;
718
+ });
719
+ return phases;
720
+ }
721
+ updatePlanStatus(plan) {
722
+ const completed = plan.tasks.filter(t => t.status === types_1.TaskStatus.COMPLETED).length;
723
+ const inProgress = plan.tasks.filter(t => t.status === types_1.TaskStatus.IN_PROGRESS).length;
724
+ const failed = plan.tasks.filter(t => t.status === types_1.TaskStatus.FAILED).length;
725
+ if (failed > 0 && failed > plan.tasks.length * 0.3) {
726
+ plan.status = types_1.TaskStatus.FAILED;
727
+ }
728
+ else if (completed === plan.tasks.length) {
729
+ plan.status = types_1.TaskStatus.COMPLETED;
730
+ }
731
+ else if (inProgress > 0 || completed > 0) {
732
+ plan.status = types_1.TaskStatus.IN_PROGRESS;
733
+ }
734
+ }
735
+ isOnTrack(plan) {
736
+ if (!plan.timeline.endDate)
737
+ return true;
738
+ const elapsed = Date.now() - plan.timeline.startDate.getTime();
739
+ const total = plan.timeline.endDate.getTime() - plan.timeline.startDate.getTime();
740
+ const expectedProgress = elapsed / total;
741
+ const completedTasks = plan.tasks.filter(t => t.status === types_1.TaskStatus.COMPLETED).length;
742
+ const actualProgress = completedTasks / plan.tasks.length;
743
+ return actualProgress >= expectedProgress * 0.8; // Allow 20% slack
744
+ }
745
+ determineNextActions(plan) {
746
+ const actions = [];
747
+ // Find pending tasks with no incomplete dependencies
748
+ const readyTasks = plan.tasks.filter(t => {
749
+ if (t.status !== types_1.TaskStatus.PENDING)
750
+ return false;
751
+ return t.dependencies.every(depId => plan.tasks.find(t => t.id === depId)?.status === types_1.TaskStatus.COMPLETED);
752
+ });
753
+ if (readyTasks.length > 0) {
754
+ actions.push(`Start task: ${readyTasks[0].title}`);
755
+ }
756
+ // Check for at-risk tasks
757
+ const inProgressTasks = plan.tasks.filter(t => t.status === types_1.TaskStatus.IN_PROGRESS);
758
+ inProgressTasks.forEach(task => {
759
+ const trend = this.progressTracker.getProgressTrend(task.id);
760
+ if (trend === 'declining') {
761
+ actions.push(`Review task: ${task.title} (progress declining)`);
762
+ }
763
+ });
764
+ return actions;
765
+ }
766
+ }
767
+ exports.PlanningEngine = PlanningEngine;
768
+ // ============================================================================
769
+ // EXPORT SINGLETON INSTANCE
770
+ // ============================================================================
771
+ exports.planningEngine = new PlanningEngine();
772
+ // ============================================================================
773
+ // EXAMPLE USAGE
774
+ // ============================================================================
775
+ /*
776
+ // Create a plan
777
+ const plan = planningEngine.createPlan(
778
+ 'Build a scalable microservices architecture with AI capabilities',
779
+ {
780
+ resources: [
781
+ {
782
+ id: 'dev1',
783
+ type: 'human',
784
+ name: 'Senior Developer',
785
+ availability: 0.8,
786
+ skills: ['backend', 'microservices', 'typescript']
787
+ },
788
+ {
789
+ id: 'dev2',
790
+ type: 'human',
791
+ name: 'ML Engineer',
792
+ availability: 0.6,
793
+ skills: ['machine_learning', 'python', 'tensorflow']
794
+ }
795
+ ],
796
+ deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30 days
797
+ }
798
+ );
799
+
800
+ // Update task progress
801
+ planningEngine.updateTaskProgress(plan.id, plan.tasks[0].id, 50, TaskStatus.IN_PROGRESS);
802
+ planningEngine.updateTaskProgress(plan.id, plan.tasks[0].id, 100, TaskStatus.COMPLETED);
803
+
804
+ // Generate progress report
805
+ const report = planningEngine.generateProgressReport(plan.id);
806
+ console.log(`Progress: ${report.overallProgress}%`);
807
+ console.log(`On track: ${report.onTrack}`);
808
+ console.log(`Next actions: ${report.nextActions.join(', ')}`);
809
+
810
+ // Adjust plan
811
+ const adjustedPlan = planningEngine.adjustPlan(plan.id, {
812
+ addTasks: [{
813
+ title: 'Security audit',
814
+ description: 'Perform security review',
815
+ priority: Priority.HIGH,
816
+ status: TaskStatus.PENDING,
817
+ estimatedDuration: 120,
818
+ dependencies: [],
819
+ subtasks: [],
820
+ tags: ['security']
821
+ }]
822
+ });
823
+ */
824
+ //# sourceMappingURL=planning.js.map