gthinking 1.3.0 → 2.1.1

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 (271) hide show
  1. package/.eslintrc.js +34 -0
  2. package/ANALYSIS_SUMMARY.md +363 -0
  3. package/README.md +230 -250
  4. package/dist/analysis/analysis-engine.d.ts +63 -0
  5. package/dist/analysis/analysis-engine.d.ts.map +1 -0
  6. package/dist/analysis/analysis-engine.js +322 -0
  7. package/dist/analysis/analysis-engine.js.map +1 -0
  8. package/dist/core/config.d.ts +1419 -0
  9. package/dist/core/config.d.ts.map +1 -0
  10. package/dist/core/config.js +361 -0
  11. package/dist/core/config.js.map +1 -0
  12. package/dist/core/engine.d.ts +176 -0
  13. package/dist/core/engine.d.ts.map +1 -0
  14. package/dist/core/engine.js +604 -0
  15. package/dist/core/engine.js.map +1 -0
  16. package/dist/core/errors.d.ts +153 -0
  17. package/dist/core/errors.d.ts.map +1 -0
  18. package/dist/core/errors.js +287 -0
  19. package/dist/core/errors.js.map +1 -0
  20. package/dist/core/index.d.ts +7 -0
  21. package/dist/core/index.d.ts.map +1 -0
  22. package/dist/{types.js → core/index.js} +8 -4
  23. package/dist/core/index.js.map +1 -0
  24. package/dist/core/pipeline.d.ts +121 -0
  25. package/dist/core/pipeline.d.ts.map +1 -0
  26. package/dist/core/pipeline.js +289 -0
  27. package/dist/core/pipeline.js.map +1 -0
  28. package/dist/core/rate-limiter.d.ts +58 -0
  29. package/dist/core/rate-limiter.d.ts.map +1 -0
  30. package/dist/core/rate-limiter.js +133 -0
  31. package/dist/core/rate-limiter.js.map +1 -0
  32. package/dist/core/session-manager.d.ts +96 -0
  33. package/dist/core/session-manager.d.ts.map +1 -0
  34. package/dist/core/session-manager.js +223 -0
  35. package/dist/core/session-manager.js.map +1 -0
  36. package/dist/creativity/creativity-engine.d.ts +6 -0
  37. package/dist/creativity/creativity-engine.d.ts.map +1 -0
  38. package/dist/creativity/creativity-engine.js +17 -0
  39. package/dist/creativity/creativity-engine.js.map +1 -0
  40. package/dist/index.d.ts +24 -32
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +130 -104
  43. package/dist/index.js.map +1 -1
  44. package/dist/learning/learning-engine.d.ts +6 -0
  45. package/dist/learning/learning-engine.d.ts.map +1 -0
  46. package/dist/learning/learning-engine.js +17 -0
  47. package/dist/learning/learning-engine.js.map +1 -0
  48. package/dist/llm/index.d.ts +10 -0
  49. package/dist/llm/index.d.ts.map +1 -0
  50. package/dist/llm/index.js +26 -0
  51. package/dist/llm/index.js.map +1 -0
  52. package/dist/llm/llm-service.d.ts +109 -0
  53. package/dist/llm/llm-service.d.ts.map +1 -0
  54. package/dist/llm/llm-service.js +224 -0
  55. package/dist/llm/llm-service.js.map +1 -0
  56. package/dist/llm/providers/base.d.ts +85 -0
  57. package/dist/llm/providers/base.d.ts.map +1 -0
  58. package/dist/llm/providers/base.js +57 -0
  59. package/dist/llm/providers/base.js.map +1 -0
  60. package/dist/llm/providers/cli.d.ts +23 -0
  61. package/dist/llm/providers/cli.d.ts.map +1 -0
  62. package/dist/llm/providers/cli.js +158 -0
  63. package/dist/llm/providers/cli.js.map +1 -0
  64. package/dist/llm/providers/gemini.d.ts +30 -0
  65. package/dist/llm/providers/gemini.d.ts.map +1 -0
  66. package/dist/llm/providers/gemini.js +168 -0
  67. package/dist/llm/providers/gemini.js.map +1 -0
  68. package/dist/llm/sanitization.d.ts +50 -0
  69. package/dist/llm/sanitization.d.ts.map +1 -0
  70. package/dist/llm/sanitization.js +149 -0
  71. package/dist/llm/sanitization.js.map +1 -0
  72. package/dist/{server.d.ts.map → mcp/server.d.ts.map} +1 -1
  73. package/dist/mcp/server.js +108 -0
  74. package/dist/mcp/server.js.map +1 -0
  75. package/dist/planning/planning-engine.d.ts +6 -0
  76. package/dist/planning/planning-engine.d.ts.map +1 -0
  77. package/dist/planning/planning-engine.js +17 -0
  78. package/dist/planning/planning-engine.js.map +1 -0
  79. package/dist/reasoning/reasoning-engine.d.ts +6 -0
  80. package/dist/reasoning/reasoning-engine.d.ts.map +1 -0
  81. package/dist/reasoning/reasoning-engine.js +17 -0
  82. package/dist/reasoning/reasoning-engine.js.map +1 -0
  83. package/dist/search/search-engine.d.ts +99 -0
  84. package/dist/search/search-engine.d.ts.map +1 -0
  85. package/dist/search/search-engine.js +271 -0
  86. package/dist/search/search-engine.js.map +1 -0
  87. package/dist/synthesis/synthesis-engine.d.ts +6 -0
  88. package/dist/synthesis/synthesis-engine.d.ts.map +1 -0
  89. package/dist/synthesis/synthesis-engine.js +17 -0
  90. package/dist/synthesis/synthesis-engine.js.map +1 -0
  91. package/dist/types/analysis.d.ts +1534 -49
  92. package/dist/types/analysis.d.ts.map +1 -1
  93. package/dist/types/analysis.js +250 -0
  94. package/dist/types/analysis.js.map +1 -1
  95. package/dist/types/core.d.ts +257 -30
  96. package/dist/types/core.d.ts.map +1 -1
  97. package/dist/types/core.js +148 -18
  98. package/dist/types/core.js.map +1 -1
  99. package/dist/types/creativity.d.ts +2871 -56
  100. package/dist/types/creativity.d.ts.map +1 -1
  101. package/dist/types/creativity.js +195 -0
  102. package/dist/types/creativity.js.map +1 -1
  103. package/dist/types/index.d.ts +6 -2
  104. package/dist/types/index.d.ts.map +1 -1
  105. package/dist/types/index.js +17 -2
  106. package/dist/types/index.js.map +1 -1
  107. package/dist/types/learning.d.ts +851 -61
  108. package/dist/types/learning.d.ts.map +1 -1
  109. package/dist/types/learning.js +155 -0
  110. package/dist/types/learning.js.map +1 -1
  111. package/dist/types/planning.d.ts +2223 -71
  112. package/dist/types/planning.d.ts.map +1 -1
  113. package/dist/types/planning.js +190 -0
  114. package/dist/types/planning.js.map +1 -1
  115. package/dist/types/reasoning.d.ts +2209 -72
  116. package/dist/types/reasoning.d.ts.map +1 -1
  117. package/dist/types/reasoning.js +200 -1
  118. package/dist/types/reasoning.js.map +1 -1
  119. package/dist/types/search.d.ts +981 -53
  120. package/dist/types/search.d.ts.map +1 -1
  121. package/dist/types/search.js +137 -0
  122. package/dist/types/search.js.map +1 -1
  123. package/dist/types/synthesis.d.ts +583 -38
  124. package/dist/types/synthesis.d.ts.map +1 -1
  125. package/dist/types/synthesis.js +138 -0
  126. package/dist/types/synthesis.js.map +1 -1
  127. package/dist/utils/cache.d.ts +144 -0
  128. package/dist/utils/cache.d.ts.map +1 -0
  129. package/dist/utils/cache.js +288 -0
  130. package/dist/utils/cache.js.map +1 -0
  131. package/dist/utils/id-generator.d.ts +89 -0
  132. package/dist/utils/id-generator.d.ts.map +1 -0
  133. package/dist/utils/id-generator.js +132 -0
  134. package/dist/utils/id-generator.js.map +1 -0
  135. package/dist/utils/index.d.ts +11 -0
  136. package/dist/utils/index.d.ts.map +1 -0
  137. package/dist/utils/index.js +33 -0
  138. package/dist/utils/index.js.map +1 -0
  139. package/dist/utils/logger.d.ts +142 -0
  140. package/dist/utils/logger.d.ts.map +1 -0
  141. package/dist/utils/logger.js +248 -0
  142. package/dist/utils/logger.js.map +1 -0
  143. package/dist/utils/metrics.d.ts +149 -0
  144. package/dist/utils/metrics.d.ts.map +1 -0
  145. package/dist/utils/metrics.js +296 -0
  146. package/dist/utils/metrics.js.map +1 -0
  147. package/dist/utils/timer.d.ts +7 -0
  148. package/dist/utils/timer.d.ts.map +1 -0
  149. package/dist/utils/timer.js +17 -0
  150. package/dist/utils/timer.js.map +1 -0
  151. package/dist/utils/validation.d.ts +147 -0
  152. package/dist/utils/validation.d.ts.map +1 -0
  153. package/dist/utils/validation.js +275 -0
  154. package/dist/utils/validation.js.map +1 -0
  155. package/docs/API.md +411 -0
  156. package/docs/ARCHITECTURE.md +271 -0
  157. package/docs/CHANGELOG.md +283 -0
  158. package/jest.config.js +28 -0
  159. package/package.json +43 -30
  160. package/src/analysis/analysis-engine.ts +383 -0
  161. package/src/core/config.ts +406 -0
  162. package/src/core/engine.ts +785 -0
  163. package/src/core/errors.ts +349 -0
  164. package/src/core/index.ts +12 -0
  165. package/src/core/pipeline.ts +424 -0
  166. package/src/core/rate-limiter.ts +155 -0
  167. package/src/core/session-manager.ts +269 -0
  168. package/src/creativity/creativity-engine.ts +14 -0
  169. package/src/index.ts +178 -0
  170. package/src/learning/learning-engine.ts +14 -0
  171. package/src/llm/index.ts +10 -0
  172. package/src/llm/llm-service.ts +285 -0
  173. package/src/llm/providers/base.ts +146 -0
  174. package/src/llm/providers/cli.ts +186 -0
  175. package/src/llm/providers/gemini.ts +201 -0
  176. package/src/llm/sanitization.ts +178 -0
  177. package/src/mcp/server.ts +117 -0
  178. package/src/planning/planning-engine.ts +14 -0
  179. package/src/reasoning/reasoning-engine.ts +14 -0
  180. package/src/search/search-engine.ts +333 -0
  181. package/src/synthesis/synthesis-engine.ts +14 -0
  182. package/src/types/analysis.ts +337 -0
  183. package/src/types/core.ts +342 -0
  184. package/src/types/creativity.ts +268 -0
  185. package/src/types/index.ts +31 -0
  186. package/src/types/learning.ts +215 -0
  187. package/src/types/planning.ts +251 -0
  188. package/src/types/reasoning.ts +288 -0
  189. package/src/types/search.ts +192 -0
  190. package/src/types/synthesis.ts +187 -0
  191. package/src/utils/cache.ts +363 -0
  192. package/src/utils/id-generator.ts +135 -0
  193. package/src/utils/index.ts +22 -0
  194. package/src/utils/logger.ts +290 -0
  195. package/src/utils/metrics.ts +380 -0
  196. package/src/utils/timer.ts +15 -0
  197. package/src/utils/validation.ts +297 -0
  198. package/tests/setup.ts +22 -0
  199. package/tests/unit/cache.test.ts +189 -0
  200. package/tests/unit/engine.test.ts +179 -0
  201. package/tests/unit/validation.test.ts +218 -0
  202. package/tsconfig.json +17 -12
  203. package/GEMINI.md +0 -68
  204. package/analysis.ts +0 -1063
  205. package/creativity.ts +0 -1055
  206. package/dist/analysis.d.ts +0 -54
  207. package/dist/analysis.d.ts.map +0 -1
  208. package/dist/analysis.js +0 -866
  209. package/dist/analysis.js.map +0 -1
  210. package/dist/creativity.d.ts +0 -81
  211. package/dist/creativity.d.ts.map +0 -1
  212. package/dist/creativity.js +0 -828
  213. package/dist/creativity.js.map +0 -1
  214. package/dist/engine.d.ts +0 -90
  215. package/dist/engine.d.ts.map +0 -1
  216. package/dist/engine.js +0 -720
  217. package/dist/engine.js.map +0 -1
  218. package/dist/examples.d.ts +0 -7
  219. package/dist/examples.d.ts.map +0 -1
  220. package/dist/examples.js +0 -506
  221. package/dist/examples.js.map +0 -1
  222. package/dist/learning.d.ts +0 -72
  223. package/dist/learning.d.ts.map +0 -1
  224. package/dist/learning.js +0 -615
  225. package/dist/learning.js.map +0 -1
  226. package/dist/llm-service.d.ts +0 -21
  227. package/dist/llm-service.d.ts.map +0 -1
  228. package/dist/llm-service.js +0 -100
  229. package/dist/llm-service.js.map +0 -1
  230. package/dist/planning.d.ts +0 -62
  231. package/dist/planning.d.ts.map +0 -1
  232. package/dist/planning.js +0 -886
  233. package/dist/planning.js.map +0 -1
  234. package/dist/reasoning.d.ts +0 -73
  235. package/dist/reasoning.d.ts.map +0 -1
  236. package/dist/reasoning.js +0 -845
  237. package/dist/reasoning.js.map +0 -1
  238. package/dist/search-discovery.d.ts +0 -73
  239. package/dist/search-discovery.d.ts.map +0 -1
  240. package/dist/search-discovery.js +0 -548
  241. package/dist/search-discovery.js.map +0 -1
  242. package/dist/server.js +0 -113
  243. package/dist/server.js.map +0 -1
  244. package/dist/types/engine.d.ts +0 -55
  245. package/dist/types/engine.d.ts.map +0 -1
  246. package/dist/types/engine.js +0 -3
  247. package/dist/types/engine.js.map +0 -1
  248. package/dist/types.d.ts +0 -6
  249. package/dist/types.d.ts.map +0 -1
  250. package/dist/types.js.map +0 -1
  251. package/engine.ts +0 -1009
  252. package/examples.ts +0 -717
  253. package/index.ts +0 -106
  254. package/learning.ts +0 -779
  255. package/llm-service.ts +0 -120
  256. package/planning.ts +0 -1101
  257. package/reasoning.ts +0 -1079
  258. package/search-discovery.ts +0 -700
  259. package/server.ts +0 -115
  260. package/types/analysis.ts +0 -69
  261. package/types/core.ts +0 -90
  262. package/types/creativity.ts +0 -72
  263. package/types/engine.ts +0 -60
  264. package/types/index.ts +0 -9
  265. package/types/learning.ts +0 -69
  266. package/types/planning.ts +0 -85
  267. package/types/reasoning.ts +0 -92
  268. package/types/search.ts +0 -58
  269. package/types/synthesis.ts +0 -43
  270. package/types.ts +0 -6
  271. /package/dist/{server.d.ts → mcp/server.d.ts} +0 -0
package/planning.ts DELETED
@@ -1,1101 +0,0 @@
1
- /**
2
- * Planning Module
3
- * Task decomposition, prioritization, resource allocation, and progress tracking
4
- */
5
-
6
- import {
7
- Plan,
8
- Task,
9
- Milestone,
10
- Resource,
11
- Timeline,
12
- Phase,
13
- ProgressReport,
14
- Risk,
15
- Priority,
16
- TaskStatus,
17
- ThinkingEvent,
18
- ThinkingError,
19
- ThinkingStage
20
- } from './types';
21
- import { EventEmitter } from 'events';
22
-
23
- // ============================================================================
24
- // TASK DECOMPOSITION ENGINE
25
- // ============================================================================
26
-
27
- interface DecompositionRule {
28
- pattern: RegExp;
29
- subtasks: string[];
30
- dependencies: string[][];
31
- }
32
-
33
- class TaskDecompositionEngine {
34
- private decompositionRules: DecompositionRule[] = [
35
- {
36
- pattern: /build|create|develop|implement/i,
37
- subtasks: [
38
- 'Research and requirements gathering',
39
- 'Design and architecture',
40
- 'Implementation',
41
- 'Testing and validation',
42
- 'Deployment'
43
- ],
44
- dependencies: [[], ['0'], ['1'], ['2'], ['3']]
45
- },
46
- {
47
- pattern: /analyze|research|investigate/i,
48
- subtasks: [
49
- 'Define scope and objectives',
50
- 'Gather existing data',
51
- 'Conduct analysis',
52
- 'Document findings',
53
- 'Present recommendations'
54
- ],
55
- dependencies: [[], ['0'], ['1'], ['2'], ['3']]
56
- },
57
- {
58
- pattern: /optimize|improve|enhance/i,
59
- subtasks: [
60
- 'Current state assessment',
61
- 'Identify improvement areas',
62
- 'Design improvements',
63
- 'Implement changes',
64
- 'Measure results'
65
- ],
66
- dependencies: [[], ['0'], ['1'], ['2'], ['3']]
67
- }
68
- ];
69
-
70
- decompose(goal: string): { subtasks: string[]; dependencies: string[][] } {
71
- // Find matching decomposition rule
72
- for (const rule of this.decompositionRules) {
73
- if (rule.pattern.test(goal)) {
74
- return {
75
- subtasks: rule.subtasks,
76
- dependencies: rule.dependencies
77
- };
78
- }
79
- }
80
-
81
- // Default decomposition
82
- return {
83
- subtasks: [
84
- 'Understand requirements',
85
- 'Plan approach',
86
- 'Execute plan',
87
- 'Review and validate'
88
- ],
89
- dependencies: [[], ['0'], ['1'], ['2']]
90
- };
91
- }
92
-
93
- estimateComplexity(task: string): number {
94
- // Estimate complexity based on keywords
95
- const complexityIndicators = [
96
- { keywords: ['complex', 'difficult', 'challenging', 'advanced'], weight: 0.9 },
97
- { keywords: ['simple', 'easy', 'basic', 'straightforward'], weight: 0.3 },
98
- { keywords: ['research', 'analysis', 'investigation'], weight: 0.7 },
99
- { keywords: ['implement', 'build', 'develop'], weight: 0.8 }
100
- ];
101
-
102
- const taskLower = task.toLowerCase();
103
- let complexity = 0.5; // Default
104
-
105
- complexityIndicators.forEach(indicator => {
106
- if (indicator.keywords.some(kw => taskLower.includes(kw))) {
107
- complexity = indicator.weight;
108
- }
109
- });
110
-
111
- // Adjust based on task length (longer tasks tend to be more complex)
112
- const wordCount = task.split(/\s+/).length;
113
- complexity += Math.min(0.2, wordCount * 0.01);
114
-
115
- return Math.min(1, complexity);
116
- }
117
-
118
- estimateDuration(task: string, complexity: number): number {
119
- // Duration in minutes
120
- const baseDuration = 30;
121
- const complexityMultiplier = 1 + complexity * 4; // 1x to 5x
122
-
123
- return Math.round(baseDuration * complexityMultiplier);
124
- }
125
- }
126
-
127
- // ============================================================================
128
- // PRIORITIZATION ENGINE
129
- // ============================================================================
130
-
131
- interface PrioritizationCriteria {
132
- urgency: number;
133
- importance: number;
134
- effort: number;
135
- risk: number;
136
- dependencies: number;
137
- }
138
-
139
- class PrioritizationEngine {
140
- private weights = {
141
- urgency: 0.25,
142
- importance: 0.3,
143
- effort: 0.2,
144
- risk: 0.15,
145
- dependencies: 0.1
146
- };
147
-
148
- prioritize(tasks: Task[]): Task[] {
149
- const scoredTasks = tasks.map(task => ({
150
- task,
151
- score: this.calculatePriorityScore(task)
152
- }));
153
-
154
- return scoredTasks
155
- .sort((a, b) => b.score - a.score)
156
- .map(({ task }) => task);
157
- }
158
-
159
- private calculatePriorityScore(task: Task): number {
160
- const criteria = this.assessCriteria(task);
161
-
162
- // Calculate weighted score
163
- let score = 0;
164
- score += criteria.urgency * this.weights.urgency;
165
- score += criteria.importance * this.weights.importance;
166
- score += (1 - criteria.effort) * this.weights.effort; // Lower effort = higher priority
167
- score += (1 - criteria.risk) * this.weights.risk; // Lower risk = higher priority
168
- score += (1 - criteria.dependencies) * this.weights.dependencies; // Fewer deps = higher priority
169
-
170
- return score;
171
- }
172
-
173
- private assessCriteria(task: Task): PrioritizationCriteria {
174
- return {
175
- urgency: this.assessUrgency(task),
176
- importance: this.assessImportance(task),
177
- effort: this.assessEffort(task),
178
- risk: this.assessRisk(task),
179
- dependencies: this.assessDependencies(task)
180
- };
181
- }
182
-
183
- private assessUrgency(task: Task): number {
184
- const urgencyKeywords = ['urgent', 'asap', 'immediate', 'critical', 'deadline'];
185
- const taskText = `${task.title} ${task.description}`.toLowerCase();
186
-
187
- if (task.priority === Priority.CRITICAL) return 1;
188
- if (task.priority === Priority.HIGH) return 0.8;
189
-
190
- const matches = urgencyKeywords.filter(kw => taskText.includes(kw)).length;
191
- return Math.min(1, matches * 0.3 + (task.priority === Priority.MEDIUM ? 0.3 : task.priority === Priority.LOW ? 0.2 : 0.1));
192
- }
193
-
194
- private assessImportance(task: Task): number {
195
- const importanceKeywords = ['essential', 'crucial', 'key', 'important', 'core'];
196
- const taskText = `${task.title} ${task.description}`.toLowerCase();
197
-
198
- if (task.tags.includes('critical')) return 1;
199
-
200
- const matches = importanceKeywords.filter(kw => taskText.includes(kw)).length;
201
- return Math.min(1, matches * 0.25 + 0.3);
202
- }
203
-
204
- private assessEffort(task: Task): number {
205
- // Normalize estimated duration (assuming max 8 hours)
206
- return Math.min(1, task.estimatedDuration / 480);
207
- }
208
-
209
- private assessRisk(task: Task): number {
210
- const riskKeywords = ['risk', 'uncertain', 'unknown', 'complex', 'difficult'];
211
- const taskText = `${task.title} ${task.description}`.toLowerCase();
212
-
213
- const matches = riskKeywords.filter(kw => taskText.includes(kw)).length;
214
- return Math.min(1, matches * 0.3);
215
- }
216
-
217
- private assessDependencies(task: Task): number {
218
- return Math.min(1, task.dependencies.length / 5);
219
- }
220
-
221
- /**
222
- * Calculate critical path
223
- */
224
- calculateCriticalPath(tasks: Task[]): string[] {
225
- const taskMap = new Map(tasks.map(t => [t.id, t]));
226
- const visited = new Set<string>();
227
- const path: string[] = [];
228
-
229
- const visit = (taskId: string, currentPath: string[] = []): number => {
230
- if (visited.has(taskId)) return 0;
231
- if (currentPath.includes(taskId)) return 0; // Cycle detected
232
-
233
- const task = taskMap.get(taskId);
234
- if (!task) return 0;
235
-
236
- let maxPathDuration = task.estimatedDuration;
237
-
238
- for (const depId of task.dependencies) {
239
- const depDuration = visit(depId, [...currentPath, taskId]);
240
- maxPathDuration = Math.max(maxPathDuration, task.estimatedDuration + depDuration);
241
- }
242
-
243
- visited.add(taskId);
244
- path.push(taskId);
245
-
246
- return maxPathDuration;
247
- };
248
-
249
- // Find the longest path
250
- let maxDuration = 0;
251
- let criticalPath: string[] = [];
252
-
253
- for (const task of tasks) {
254
- visited.clear();
255
- path.length = 0;
256
- const duration = visit(task.id);
257
-
258
- if (duration > maxDuration) {
259
- maxDuration = duration;
260
- criticalPath = [...path];
261
- }
262
- }
263
-
264
- return criticalPath;
265
- }
266
- }
267
-
268
- // ============================================================================
269
- // RESOURCE ALLOCATOR
270
- // ============================================================================
271
-
272
- class ResourceAllocator {
273
- private resources: Map<string, Resource> = new Map();
274
-
275
- addResource(resource: Resource): void {
276
- this.resources.set(resource.id, resource);
277
- }
278
-
279
- allocate(tasks: Task[]): Map<string, string[]> {
280
- const allocation = new Map<string, string[]>();
281
- const resourceAvailability = new Map<string, number>();
282
-
283
- // Initialize availability
284
- this.resources.forEach((resource, id) => {
285
- resourceAvailability.set(id, resource.availability);
286
- });
287
-
288
- // Allocate resources to tasks
289
- for (const task of tasks) {
290
- const suitableResources = this.findSuitableResources(task);
291
- const allocated: string[] = [];
292
-
293
- for (const resource of suitableResources) {
294
- const available = resourceAvailability.get(resource.id) || 0;
295
- if (available > 0) {
296
- allocated.push(resource.id);
297
- resourceAvailability.set(resource.id, available - 1);
298
- }
299
- }
300
-
301
- allocation.set(task.id, allocated);
302
- }
303
-
304
- return allocation;
305
- }
306
-
307
- private findSuitableResources(task: Task): Resource[] {
308
- return Array.from(this.resources.values())
309
- .filter(resource => {
310
- // Check if resource skills match task requirements
311
- if (task.tags.length > 0 && resource.skills) {
312
- return task.tags.some(tag =>
313
- resource.skills!.some(skill =>
314
- skill.toLowerCase().includes(tag.toLowerCase()) ||
315
- tag.toLowerCase().includes(skill.toLowerCase())
316
- )
317
- );
318
- }
319
- return true;
320
- })
321
- .sort((a, b) => b.availability - a.availability);
322
- }
323
-
324
- checkOverallocation(): Array<{ resourceId: string; overallocation: number }> {
325
- const overallocations: Array<{ resourceId: string; overallocation: number }> = [];
326
-
327
- this.resources.forEach((resource, id) => {
328
- if (resource.availability < 0) {
329
- overallocations.push({
330
- resourceId: id,
331
- overallocation: Math.abs(resource.availability)
332
- });
333
- }
334
- });
335
-
336
- return overallocations;
337
- }
338
-
339
- getResourceUtilization(): Map<string, number> {
340
- const utilization = new Map<string, number>();
341
-
342
- this.resources.forEach((resource, id) => {
343
- // Calculate utilization (simplified)
344
- utilization.set(id, 1 - resource.availability);
345
- });
346
-
347
- return utilization;
348
- }
349
- }
350
-
351
- // ============================================================================
352
- // PROGRESS TRACKER
353
- // ============================================================================
354
-
355
- class ProgressTracker {
356
- private taskHistory: Map<string, Array<{ timestamp: Date; status: TaskStatus; progress: number }>> = new Map();
357
-
358
- recordProgress(taskId: string, status: TaskStatus, progress: number): void {
359
- if (!this.taskHistory.has(taskId)) {
360
- this.taskHistory.set(taskId, []);
361
- }
362
-
363
- this.taskHistory.get(taskId)!.push({
364
- timestamp: new Date(),
365
- status,
366
- progress: Math.min(100, Math.max(0, progress))
367
- });
368
- }
369
-
370
- getProgress(taskId: string): number {
371
- const history = this.taskHistory.get(taskId);
372
- if (!history || history.length === 0) return 0;
373
- return history[history.length - 1].progress;
374
- }
375
-
376
- calculateVelocity(taskId: string): number {
377
- const history = this.taskHistory.get(taskId);
378
- if (!history || history.length < 2) return 0;
379
-
380
- const first = history[0];
381
- const last = history[history.length - 1];
382
- const timeDiff = last.timestamp.getTime() - first.timestamp.getTime();
383
- const progressDiff = last.progress - first.progress;
384
-
385
- return timeDiff > 0 ? (progressDiff / timeDiff) * 3600000 : 0; // Progress per hour
386
- }
387
-
388
- predictCompletion(taskId: string, totalWork: number): Date | null {
389
- const velocity = this.calculateVelocity(taskId);
390
- const currentProgress = this.getProgress(taskId);
391
-
392
- if (velocity <= 0 || currentProgress >= 100) return null;
393
-
394
- const remainingWork = totalWork * (1 - currentProgress / 100);
395
- const hoursRemaining = remainingWork / velocity;
396
-
397
- return new Date(Date.now() + hoursRemaining * 3600000);
398
- }
399
-
400
- getProgressTrend(taskId: string): 'improving' | 'stable' | 'declining' {
401
- const history = this.taskHistory.get(taskId);
402
- if (!history || history.length < 3) return 'stable';
403
-
404
- const recent = history.slice(-3);
405
- const velocities: number[] = [];
406
-
407
- for (let i = 1; i < recent.length; i++) {
408
- const timeDiff = recent[i].timestamp.getTime() - recent[i - 1].timestamp.getTime();
409
- const progressDiff = recent[i].progress - recent[i - 1].progress;
410
- velocities.push(timeDiff > 0 ? progressDiff / timeDiff : 0);
411
- }
412
-
413
- const avgVelocity = velocities.reduce((a, b) => a + b, 0) / velocities.length;
414
- const firstVelocity = velocities[0];
415
-
416
- if (avgVelocity > firstVelocity * 1.2) return 'improving';
417
- if (avgVelocity < firstVelocity * 0.8) return 'declining';
418
- return 'stable';
419
- }
420
- }
421
-
422
- // ============================================================================
423
- // RISK ANALYZER
424
- // ============================================================================
425
-
426
- class RiskAnalyzer {
427
- private knownRisks: Map<string, Risk> = new Map();
428
-
429
- analyzeRisks(tasks: Task[], resources: Resource[]): Risk[] {
430
- const risks: Risk[] = [];
431
-
432
- // Analyze task-related risks
433
- tasks.forEach(task => {
434
- const taskRisks = this.identifyTaskRisks(task);
435
- risks.push(...taskRisks);
436
- });
437
-
438
- // Analyze resource-related risks
439
- const resourceRisks = this.identifyResourceRisks(tasks, resources);
440
- risks.push(...resourceRisks);
441
-
442
- // Analyze schedule-related risks
443
- const scheduleRisks = this.identifyScheduleRisks(tasks);
444
- risks.push(...scheduleRisks);
445
-
446
- // Sort by risk score (probability * impact)
447
- return risks
448
- .map(risk => ({ ...risk, riskScore: risk.probability * risk.impact }))
449
- .sort((a, b) => (b as any).riskScore - (a as any).riskScore);
450
- }
451
-
452
- private identifyTaskRisks(task: Task): Risk[] {
453
- const risks: Risk[] = [];
454
-
455
- // Complexity risk
456
- if (task.estimatedDuration > 240) { // > 4 hours
457
- risks.push({
458
- id: `risk_complexity_${task.id}`,
459
- description: `Task "${task.title}" is complex and may take longer than estimated`,
460
- probability: 0.6,
461
- impact: 0.7,
462
- mitigation: 'Break down into smaller subtasks',
463
- status: 'identified'
464
- });
465
- }
466
-
467
- // Dependency risk
468
- if (task.dependencies.length > 3) {
469
- risks.push({
470
- id: `risk_deps_${task.id}`,
471
- description: `Task "${task.title}" has many dependencies`,
472
- probability: 0.5,
473
- impact: 0.6,
474
- mitigation: 'Monitor dependencies closely and have backup plans',
475
- status: 'identified'
476
- });
477
- }
478
-
479
- // Uncertainty risk
480
- const uncertaintyKeywords = ['unclear', 'unknown', 'uncertain', 'tbd', 'tba'];
481
- const taskText = `${task.title} ${task.description}`.toLowerCase();
482
- if (uncertaintyKeywords.some(kw => taskText.includes(kw))) {
483
- risks.push({
484
- id: `risk_uncertainty_${task.id}`,
485
- description: `Task "${task.title}" has unclear requirements`,
486
- probability: 0.7,
487
- impact: 0.5,
488
- mitigation: 'Clarify requirements before starting',
489
- status: 'identified'
490
- });
491
- }
492
-
493
- return risks;
494
- }
495
-
496
- private identifyResourceRisks(tasks: Task[], resources: Resource[]): Risk[] {
497
- const risks: Risk[] = [];
498
-
499
- // Resource availability risk
500
- const totalAvailability = resources.reduce((sum, r) => sum + r.availability, 0);
501
- const totalWork = tasks.reduce((sum, t) => sum + t.estimatedDuration, 0);
502
-
503
- if (totalWork > totalAvailability * 480) { // Assuming 8 hours per availability unit
504
- risks.push({
505
- id: 'risk_resource_availability',
506
- description: 'Insufficient resources for planned work',
507
- probability: 0.8,
508
- impact: 0.9,
509
- mitigation: 'Add more resources or extend timeline',
510
- status: 'identified'
511
- });
512
- }
513
-
514
- return risks;
515
- }
516
-
517
- private identifyScheduleRisks(tasks: Task[]): Risk[] {
518
- const risks: Risk[] = [];
519
-
520
- // Check for tight schedules
521
- const criticalTasks = tasks.filter(t => t.priority === Priority.CRITICAL);
522
- if (criticalTasks.length > tasks.length * 0.3) {
523
- risks.push({
524
- id: 'risk_tight_schedule',
525
- description: 'Too many critical tasks may lead to schedule slip',
526
- probability: 0.6,
527
- impact: 0.7,
528
- mitigation: 'Re-prioritize and stagger critical tasks',
529
- status: 'identified'
530
- });
531
- }
532
-
533
- return risks;
534
- }
535
-
536
- updateRiskStatus(riskId: string, status: Risk['status']): void {
537
- const risk = this.knownRisks.get(riskId);
538
- if (risk) {
539
- risk.status = status;
540
- }
541
- }
542
- }
543
-
544
- // ============================================================================
545
- // MAIN PLANNING ENGINE
546
- // ============================================================================
547
-
548
- export class PlanningEngine extends EventEmitter {
549
- private decompositionEngine: TaskDecompositionEngine;
550
- private prioritizationEngine: PrioritizationEngine;
551
- private resourceAllocator: ResourceAllocator;
552
- private progressTracker: ProgressTracker;
553
- private riskAnalyzer: RiskAnalyzer;
554
- private plans: Map<string, Plan> = new Map();
555
-
556
- constructor() {
557
- super();
558
- this.decompositionEngine = new TaskDecompositionEngine();
559
- this.prioritizationEngine = new PrioritizationEngine();
560
- this.resourceAllocator = new ResourceAllocator();
561
- this.progressTracker = new ProgressTracker();
562
- this.riskAnalyzer = new RiskAnalyzer();
563
- }
564
-
565
- /**
566
- * Dynamically determine the required thinking stages based on the query
567
- */
568
- determineThinkingStages(query: string): ThinkingStage[] {
569
- const stages: ThinkingStage[] = [];
570
- const lowerQuery = query.toLowerCase();
571
-
572
- // Always include Analysis and Synthesis
573
- stages.push(ThinkingStage.ANALYSIS);
574
-
575
- // Search needed?
576
- if (
577
- lowerQuery.includes('search') ||
578
- lowerQuery.includes('find') ||
579
- lowerQuery.includes('what is') ||
580
- lowerQuery.includes('latest') ||
581
- lowerQuery.includes('research')
582
- ) {
583
- stages.push(ThinkingStage.SEARCH);
584
- }
585
-
586
- // Reasoning needed? (Default to yes for most queries unless very simple)
587
- if (
588
- lowerQuery.includes('why') ||
589
- lowerQuery.includes('how') ||
590
- lowerQuery.includes('compare') ||
591
- lowerQuery.includes('analyze') ||
592
- lowerQuery.includes('reason') ||
593
- stages.length === 1 // If only analysis so far, add reasoning
594
- ) {
595
- stages.push(ThinkingStage.REASONING);
596
- }
597
-
598
- // Creativity needed?
599
- if (
600
- lowerQuery.includes('create') ||
601
- lowerQuery.includes('idea') ||
602
- lowerQuery.includes('brainstorm') ||
603
- lowerQuery.includes('innovate') ||
604
- lowerQuery.includes('design') ||
605
- lowerQuery.includes('generate')
606
- ) {
607
- stages.push(ThinkingStage.CREATIVITY);
608
- }
609
-
610
- // Planning needed?
611
- if (
612
- lowerQuery.includes('plan') ||
613
- lowerQuery.includes('roadmap') ||
614
- lowerQuery.includes('schedule') ||
615
- lowerQuery.includes('timeline') ||
616
- lowerQuery.includes('project') ||
617
- lowerQuery.includes('steps to')
618
- ) {
619
- stages.push(ThinkingStage.PLANNING);
620
- }
621
-
622
- // Ensure logical order
623
- const orderedStages: ThinkingStage[] = [];
624
- if (stages.includes(ThinkingStage.SEARCH)) orderedStages.push(ThinkingStage.SEARCH);
625
- if (stages.includes(ThinkingStage.ANALYSIS)) orderedStages.push(ThinkingStage.ANALYSIS);
626
- if (stages.includes(ThinkingStage.REASONING)) orderedStages.push(ThinkingStage.REASONING);
627
- // Learning is usually implicit/config-based, but we can add it if context is key
628
- // stages.push(ThinkingStage.LEARNING);
629
- if (stages.includes(ThinkingStage.PLANNING)) orderedStages.push(ThinkingStage.PLANNING);
630
- if (stages.includes(ThinkingStage.CREATIVITY)) orderedStages.push(ThinkingStage.CREATIVITY);
631
-
632
- // Always synthesis at the end
633
- orderedStages.push(ThinkingStage.SYNTHESIS);
634
-
635
- return orderedStages;
636
- }
637
-
638
- /**
639
- * Create a comprehensive plan
640
- */
641
- createPlan(
642
- goal: string,
643
- options: {
644
- resources?: Resource[];
645
- deadline?: Date;
646
- constraints?: string[];
647
- } = {}
648
- ): Plan {
649
- const planId = this.generateId();
650
- const createdAt = new Date();
651
-
652
- this.emit('planning_start', {
653
- id: planId,
654
- stage: ThinkingStage.PLANNING,
655
- timestamp: createdAt,
656
- data: { goal }
657
- } as ThinkingEvent);
658
-
659
- // Decompose goal into tasks
660
- const { subtasks, dependencies } = this.decompositionEngine.decompose(goal);
661
-
662
- // Create tasks
663
- const tasks: Task[] = subtasks.map((description, index) => {
664
- const complexity = this.decompositionEngine.estimateComplexity(description);
665
- const duration = this.decompositionEngine.estimateDuration(description, complexity);
666
-
667
- return {
668
- id: `task_${planId}_${index}`,
669
- title: description,
670
- description,
671
- priority: this.inferPriority(description, index),
672
- status: TaskStatus.PENDING,
673
- estimatedDuration: duration,
674
- dependencies: dependencies[index].map(i => `task_${planId}_${i}`),
675
- subtasks: [],
676
- tags: []
677
- };
678
- });
679
-
680
- // Prioritize tasks
681
- const prioritizedTasks = this.prioritizationEngine.prioritize(tasks);
682
-
683
- // Add resources if provided
684
- if (options.resources) {
685
- options.resources.forEach(r => this.resourceAllocator.addResource(r));
686
- }
687
-
688
- // Allocate resources
689
- const resourceAllocation = this.resourceAllocator.allocate(prioritizedTasks);
690
-
691
- // Assign resources to tasks
692
- prioritizedTasks.forEach(task => {
693
- const allocated = resourceAllocation.get(task.id) || [];
694
- if (allocated.length > 0) {
695
- task.assignedTo = allocated[0];
696
- }
697
- });
698
-
699
- // Create milestones
700
- const milestones = this.createMilestones(prioritizedTasks, goal);
701
-
702
- // Create timeline
703
- const timeline = this.createTimeline(prioritizedTasks, milestones, options.deadline);
704
-
705
- // Analyze risks
706
- const risks = this.riskAnalyzer.analyzeRisks(
707
- prioritizedTasks,
708
- options.resources || []
709
- );
710
-
711
- const plan: Plan = {
712
- id: planId,
713
- goal,
714
- tasks: prioritizedTasks,
715
- milestones,
716
- resources: options.resources || [],
717
- timeline,
718
- status: TaskStatus.PENDING,
719
- createdAt,
720
- updatedAt: createdAt
721
- };
722
-
723
- this.plans.set(planId, plan);
724
-
725
- this.emit('planning_complete', {
726
- id: planId,
727
- stage: ThinkingStage.PLANNING,
728
- timestamp: new Date(),
729
- data: {
730
- plan,
731
- taskCount: tasks.length,
732
- riskCount: risks.length
733
- }
734
- } as ThinkingEvent);
735
-
736
- return plan;
737
- }
738
-
739
- /**
740
- * Update task progress
741
- */
742
- updateTaskProgress(
743
- planId: string,
744
- taskId: string,
745
- progress: number,
746
- status?: TaskStatus
747
- ): void {
748
- const plan = this.plans.get(planId);
749
- if (!plan) throw new Error(`Plan ${planId} not found`);
750
-
751
- const task = plan.tasks.find(t => t.id === taskId);
752
- if (!task) throw new Error(`Task ${taskId} not found`);
753
-
754
- const newStatus = status || (progress >= 100 ? TaskStatus.COMPLETED : progress > 0 ? TaskStatus.IN_PROGRESS : TaskStatus.PENDING);
755
-
756
- task.status = newStatus;
757
- if (newStatus === TaskStatus.COMPLETED) {
758
- task.endTime = new Date();
759
- } else if (newStatus === TaskStatus.IN_PROGRESS && !task.startTime) {
760
- task.startTime = new Date();
761
- }
762
-
763
- this.progressTracker.recordProgress(taskId, newStatus, progress);
764
-
765
- // Update plan status
766
- this.updatePlanStatus(plan);
767
- plan.updatedAt = new Date();
768
-
769
- this.emit('task_progress', {
770
- id: taskId,
771
- stage: ThinkingStage.PLANNING,
772
- timestamp: new Date(),
773
- data: { planId, taskId, progress, status: newStatus }
774
- } as ThinkingEvent);
775
- }
776
-
777
- /**
778
- * Generate progress report
779
- */
780
- generateProgressReport(planId: string): ProgressReport {
781
- const plan = this.plans.get(planId);
782
- if (!plan) throw new Error(`Plan ${planId} not found`);
783
-
784
- const completedTasks = plan.tasks.filter(t => t.status === TaskStatus.COMPLETED).length;
785
- const totalTasks = plan.tasks.length;
786
- const overallProgress = totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0;
787
-
788
- // Calculate if on track
789
- const onTrack = this.isOnTrack(plan);
790
-
791
- // Get risks
792
- const risks = this.riskAnalyzer.analyzeRisks(plan.tasks, plan.resources);
793
-
794
- // Determine next actions
795
- const nextActions = this.determineNextActions(plan);
796
-
797
- return {
798
- planId,
799
- timestamp: new Date(),
800
- overallProgress,
801
- completedTasks,
802
- totalTasks,
803
- onTrack,
804
- risks,
805
- nextActions
806
- };
807
- }
808
-
809
- /**
810
- * Adjust plan based on changes
811
- */
812
- adjustPlan(
813
- planId: string,
814
- changes: {
815
- addTasks?: Omit<Task, 'id'>[];
816
- removeTasks?: string[];
817
- updateTasks?: Partial<Task>[];
818
- newDeadline?: Date;
819
- }
820
- ): Plan {
821
- const plan = this.plans.get(planId);
822
- if (!plan) throw new Error(`Plan ${planId} not found`);
823
-
824
- // Add new tasks
825
- if (changes.addTasks) {
826
- const newTasks = changes.addTasks.map((task, index) => ({
827
- ...task,
828
- id: `task_${planId}_new_${Date.now()}_${index}`
829
- }));
830
- plan.tasks.push(...newTasks);
831
- }
832
-
833
- // Remove tasks
834
- if (changes.removeTasks) {
835
- plan.tasks = plan.tasks.filter(t => !changes.removeTasks!.includes(t.id));
836
- }
837
-
838
- // Update tasks
839
- if (changes.updateTasks) {
840
- changes.updateTasks.forEach(update => {
841
- const task = plan.tasks.find(t => t.id === (update as any).id);
842
- if (task) {
843
- Object.assign(task, update);
844
- }
845
- });
846
- }
847
-
848
- // Re-prioritize
849
- plan.tasks = this.prioritizationEngine.prioritize(plan.tasks);
850
-
851
- // Update timeline if new deadline
852
- if (changes.newDeadline) {
853
- plan.timeline.endDate = changes.newDeadline;
854
- }
855
-
856
- plan.updatedAt = new Date();
857
-
858
- this.emit('plan_adjusted', {
859
- id: planId,
860
- stage: ThinkingStage.PLANNING,
861
- timestamp: new Date(),
862
- data: { changes }
863
- } as ThinkingEvent);
864
-
865
- return plan;
866
- }
867
-
868
- /**
869
- * Get plan by ID
870
- */
871
- getPlan(planId: string): Plan | undefined {
872
- return this.plans.get(planId);
873
- }
874
-
875
- /**
876
- * Get all plans
877
- */
878
- getAllPlans(): Plan[] {
879
- return Array.from(this.plans.values());
880
- }
881
-
882
- // Private helper methods
883
- private generateId(): string {
884
- return `plan_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
885
- }
886
-
887
- private inferPriority(description: string, index: number): Priority {
888
- const lower = description.toLowerCase();
889
-
890
- if (lower.includes('critical') || lower.includes('urgent')) return Priority.CRITICAL;
891
- if (lower.includes('important') || lower.includes('key')) return Priority.HIGH;
892
- if (index < 2) return Priority.HIGH; // First tasks are usually important
893
- if (lower.includes('optional') || lower.includes('nice to have')) return Priority.LOW;
894
-
895
- return Priority.MEDIUM;
896
- }
897
-
898
- private createMilestones(tasks: Task[], goal: string): Milestone[] {
899
- const milestones: Milestone[] = [];
900
- const totalTasks = tasks.length;
901
-
902
- if (totalTasks >= 3) {
903
- milestones.push({
904
- id: `milestone_${Date.now()}_1`,
905
- title: 'Phase 1 Complete',
906
- description: 'Initial phase completed',
907
- criteria: [`Complete ${Math.ceil(totalTasks * 0.25)} tasks`],
908
- status: TaskStatus.PENDING
909
- });
910
- }
911
-
912
- if (totalTasks >= 5) {
913
- milestones.push({
914
- id: `milestone_${Date.now()}_2`,
915
- title: 'Halfway Point',
916
- description: '50% of tasks completed',
917
- criteria: [`Complete ${Math.ceil(totalTasks * 0.5)} tasks`],
918
- status: TaskStatus.PENDING
919
- });
920
- }
921
-
922
- milestones.push({
923
- id: `milestone_${Date.now()}_final`,
924
- title: 'Goal Achieved',
925
- description: goal,
926
- criteria: ['All tasks completed'],
927
- status: TaskStatus.PENDING
928
- });
929
-
930
- return milestones;
931
- }
932
-
933
- private createTimeline(
934
- tasks: Task[],
935
- milestones: Milestone[],
936
- deadline?: Date
937
- ): Timeline {
938
- const startDate = new Date();
939
- const criticalPath = this.prioritizationEngine.calculateCriticalPath(tasks);
940
-
941
- // Calculate end date based on tasks
942
- const totalDuration = tasks.reduce((sum, t) => sum + t.estimatedDuration, 0);
943
- const calculatedEndDate = new Date(startDate.getTime() + totalDuration * 60000);
944
-
945
- const endDate = deadline || calculatedEndDate;
946
-
947
- // Create phases
948
- const phases = this.createPhases(tasks);
949
-
950
- return {
951
- startDate,
952
- endDate,
953
- phases,
954
- criticalPath,
955
- buffer: deadline ?
956
- (deadline.getTime() - calculatedEndDate.getTime()) / 60000 :
957
- totalDuration * 0.2 // 20% buffer
958
- };
959
- }
960
-
961
- private createPhases(tasks: Task[]): Phase[] {
962
- const phases: Phase[] = [];
963
- const phaseNames = ['Planning', 'Execution', 'Review'];
964
- const tasksPerPhase = Math.ceil(tasks.length / phaseNames.length);
965
-
966
- let currentDate = new Date();
967
-
968
- phaseNames.forEach((name, index) => {
969
- const phaseTasks = tasks.slice(index * tasksPerPhase, (index + 1) * tasksPerPhase);
970
- const phaseDuration = phaseTasks.reduce((sum, t) => sum + t.estimatedDuration, 0);
971
-
972
- const phase: Phase = {
973
- id: `phase_${Date.now()}_${index}`,
974
- name,
975
- startDate: new Date(currentDate),
976
- endDate: new Date(currentDate.getTime() + phaseDuration * 60000),
977
- tasks: phaseTasks.map(t => t.id),
978
- dependencies: index > 0 ? [`phase_${Date.now()}_${index - 1}`] : []
979
- };
980
-
981
- phases.push(phase);
982
- currentDate = phase.endDate;
983
- });
984
-
985
- return phases;
986
- }
987
-
988
- private updatePlanStatus(plan: Plan): void {
989
- const completed = plan.tasks.filter(t => t.status === TaskStatus.COMPLETED).length;
990
- const inProgress = plan.tasks.filter(t => t.status === TaskStatus.IN_PROGRESS).length;
991
- const failed = plan.tasks.filter(t => t.status === TaskStatus.FAILED).length;
992
-
993
- if (failed > 0 && failed > plan.tasks.length * 0.3) {
994
- plan.status = TaskStatus.FAILED;
995
- } else if (completed === plan.tasks.length) {
996
- plan.status = TaskStatus.COMPLETED;
997
- } else if (inProgress > 0 || completed > 0) {
998
- plan.status = TaskStatus.IN_PROGRESS;
999
- }
1000
- }
1001
-
1002
- private isOnTrack(plan: Plan): boolean {
1003
- if (!plan.timeline.endDate) return true;
1004
-
1005
- const elapsed = Date.now() - plan.timeline.startDate.getTime();
1006
- const total = plan.timeline.endDate.getTime() - plan.timeline.startDate.getTime();
1007
- const expectedProgress = elapsed / total;
1008
-
1009
- const completedTasks = plan.tasks.filter(t => t.status === TaskStatus.COMPLETED).length;
1010
- const actualProgress = completedTasks / plan.tasks.length;
1011
-
1012
- return actualProgress >= expectedProgress * 0.8; // Allow 20% slack
1013
- }
1014
-
1015
- private determineNextActions(plan: Plan): string[] {
1016
- const actions: string[] = [];
1017
-
1018
- // Find pending tasks with no incomplete dependencies
1019
- const readyTasks = plan.tasks.filter(t => {
1020
- if (t.status !== TaskStatus.PENDING) return false;
1021
- return t.dependencies.every(depId =>
1022
- plan.tasks.find(t => t.id === depId)?.status === TaskStatus.COMPLETED
1023
- );
1024
- });
1025
-
1026
- if (readyTasks.length > 0) {
1027
- actions.push(`Start task: ${readyTasks[0].title}`);
1028
- }
1029
-
1030
- // Check for at-risk tasks
1031
- const inProgressTasks = plan.tasks.filter(t => t.status === TaskStatus.IN_PROGRESS);
1032
- inProgressTasks.forEach(task => {
1033
- const trend = this.progressTracker.getProgressTrend(task.id);
1034
- if (trend === 'declining') {
1035
- actions.push(`Review task: ${task.title} (progress declining)`);
1036
- }
1037
- });
1038
-
1039
- return actions;
1040
- }
1041
- }
1042
-
1043
- // ============================================================================
1044
- // EXPORT SINGLETON INSTANCE
1045
- // ============================================================================
1046
-
1047
- export const planningEngine = new PlanningEngine();
1048
-
1049
- // ============================================================================
1050
- // EXAMPLE USAGE
1051
- // ============================================================================
1052
-
1053
- /*
1054
- // Create a plan
1055
- const plan = planningEngine.createPlan(
1056
- 'Build a scalable microservices architecture with AI capabilities',
1057
- {
1058
- resources: [
1059
- {
1060
- id: 'dev1',
1061
- type: 'human',
1062
- name: 'Senior Developer',
1063
- availability: 0.8,
1064
- skills: ['backend', 'microservices', 'typescript']
1065
- },
1066
- {
1067
- id: 'dev2',
1068
- type: 'human',
1069
- name: 'ML Engineer',
1070
- availability: 0.6,
1071
- skills: ['machine_learning', 'python', 'tensorflow']
1072
- }
1073
- ],
1074
- deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30 days
1075
- }
1076
- );
1077
-
1078
- // Update task progress
1079
- planningEngine.updateTaskProgress(plan.id, plan.tasks[0].id, 50, TaskStatus.IN_PROGRESS);
1080
- planningEngine.updateTaskProgress(plan.id, plan.tasks[0].id, 100, TaskStatus.COMPLETED);
1081
-
1082
- // Generate progress report
1083
- const report = planningEngine.generateProgressReport(plan.id);
1084
- console.log(`Progress: ${report.overallProgress}%`);
1085
- console.log(`On track: ${report.onTrack}`);
1086
- console.log(`Next actions: ${report.nextActions.join(', ')}`);
1087
-
1088
- // Adjust plan
1089
- const adjustedPlan = planningEngine.adjustPlan(plan.id, {
1090
- addTasks: [{
1091
- title: 'Security audit',
1092
- description: 'Perform security review',
1093
- priority: Priority.HIGH,
1094
- status: TaskStatus.PENDING,
1095
- estimatedDuration: 120,
1096
- dependencies: [],
1097
- subtasks: [],
1098
- tags: ['security']
1099
- }]
1100
- });
1101
- */