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
package/creativity.ts ADDED
@@ -0,0 +1,1002 @@
1
+ /**
2
+ * Creativity Module
3
+ * Out-of-the-box thinking, idea generation, and concept connection
4
+ */
5
+
6
+ import {
7
+ CreativeSession,
8
+ CreativityTechnique,
9
+ Idea,
10
+ Connection,
11
+ DivergentPhase,
12
+ ConvergentPhase,
13
+ OutOfBoxThinking,
14
+ ReframedProblem,
15
+ ThinkingEvent,
16
+ ThinkingError,
17
+ ThinkingStage
18
+ } from './types';
19
+ import { EventEmitter } from 'events';
20
+
21
+ // ============================================================================
22
+ // BRAINSTORMING ENGINE
23
+ // ============================================================================
24
+
25
+ class BrainstormingEngine {
26
+ private ideaSeeds: Map<string, string[]> = new Map([
27
+ ['technology', ['AI', 'blockchain', 'IoT', 'cloud', 'quantum', 'biotech', 'nanotech']],
28
+ ['business', ['subscription', 'freemium', 'marketplace', 'platform', 'ecosystem']],
29
+ ['social', ['community', 'collaboration', 'sharing', 'crowdsourcing', 'network']],
30
+ ['design', ['minimalist', 'responsive', 'adaptive', 'personalized', 'immersive']]
31
+ ]);
32
+
33
+ generateIdeas(prompt: string, count: number = 10): Idea[] {
34
+ const ideas: Idea[] = [];
35
+ const domains = this.identifyDomains(prompt);
36
+
37
+ // Generate ideas using different approaches
38
+ for (let i = 0; i < count; i++) {
39
+ const technique = this.selectTechnique(i);
40
+ const idea = this.createIdea(prompt, technique, domains, i);
41
+ ideas.push(idea);
42
+ }
43
+
44
+ return ideas;
45
+ }
46
+
47
+ private identifyDomains(prompt: string): string[] {
48
+ const domains: string[] = [];
49
+ const promptLower = prompt.toLowerCase();
50
+
51
+ this.ideaSeeds.forEach((_, domain) => {
52
+ if (promptLower.includes(domain)) {
53
+ domains.push(domain);
54
+ }
55
+ });
56
+
57
+ return domains.length > 0 ? domains : ['general'];
58
+ }
59
+
60
+ private selectTechnique(index: number): CreativityTechnique {
61
+ const techniques: CreativityTechnique[] = [
62
+ 'brainstorming',
63
+ 'analogy',
64
+ 'reverse_thinking',
65
+ 'random_stimulus',
66
+ 'lateral_thinking'
67
+ ];
68
+ return techniques[index % techniques.length];
69
+ }
70
+
71
+ private createIdea(
72
+ prompt: string,
73
+ technique: CreativityTechnique,
74
+ domains: string[],
75
+ index: number
76
+ ): Idea {
77
+ const content = this.generateIdeaContent(prompt, technique, domains, index);
78
+
79
+ return {
80
+ id: `idea_${Date.now()}_${index}`,
81
+ content,
82
+ technique,
83
+ novelty: this.calculateNovelity(content),
84
+ feasibility: this.calculateFeasibility(content),
85
+ impact: this.calculateImpact(content),
86
+ relatedIdeas: [],
87
+ tags: this.extractTags(content),
88
+ generatedAt: new Date()
89
+ };
90
+ }
91
+
92
+ private generateIdeaContent(
93
+ prompt: string,
94
+ technique: CreativityTechnique,
95
+ domains: string[],
96
+ index: number
97
+ ): string {
98
+ switch (technique) {
99
+ case 'brainstorming':
100
+ return this.brainstorm(prompt, domains, index);
101
+ case 'analogy':
102
+ return this.useAnalogy(prompt, domains, index);
103
+ case 'reverse_thinking':
104
+ return this.reverseThink(prompt);
105
+ case 'random_stimulus':
106
+ return this.randomStimulus(prompt, domains);
107
+ case 'lateral_thinking':
108
+ return this.lateralThink(prompt, index);
109
+ default:
110
+ return `Idea ${index + 1}: ${prompt}`;
111
+ }
112
+ }
113
+
114
+ private brainstorm(prompt: string, domains: string[], index: number): string {
115
+ const domain = domains[index % domains.length];
116
+ const seeds = this.ideaSeeds.get(domain) || ['innovation'];
117
+ const seed = seeds[index % seeds.length];
118
+
119
+ return `Combine ${prompt} with ${seed} to create a ${domain} solution`;
120
+ }
121
+
122
+ private useAnalogy(prompt: string, domains: string[], index: number): string {
123
+ const analogies = [
124
+ 'like a nervous system for information flow',
125
+ 'like an immune system for security',
126
+ 'like an ecosystem for sustainability',
127
+ 'like a language for communication',
128
+ 'like a market for resource allocation'
129
+ ];
130
+
131
+ return `Approach ${prompt} ${analogies[index % analogies.length]}`;
132
+ }
133
+
134
+ private reverseThink(prompt: string): string {
135
+ return `Instead of ${prompt}, what if we did the opposite? ` +
136
+ `Consider: How could we achieve the inverse outcome?`;
137
+ }
138
+
139
+ private randomStimulus(prompt: string, domains: string[]): string {
140
+ const stimuli = ['nature', 'art', 'music', 'sports', 'cooking', 'architecture'];
141
+ const stimulus = stimuli[Math.floor(Math.random() * stimuli.length)];
142
+
143
+ return `Apply principles from ${stimulus} to ${prompt}`;
144
+ }
145
+
146
+ private lateralThink(prompt: string, index: number): string {
147
+ const perspectives = [
148
+ 'from a child\'s perspective',
149
+ 'from a future perspective (10 years ahead)',
150
+ 'from a resource-constrained perspective',
151
+ 'from a luxury perspective',
152
+ 'from a minimalist perspective'
153
+ ];
154
+
155
+ return `View ${prompt} ${perspectives[index % perspectives.length]}`;
156
+ }
157
+
158
+ private calculateNovelity(content: string): number {
159
+ // Higher novelty for more unique combinations
160
+ const uniqueTerms = new Set(content.toLowerCase().split(/\s+/)).size;
161
+ const totalTerms = content.split(/\s+/).length;
162
+ return Math.min(0.95, uniqueTerms / totalTerms + 0.3);
163
+ }
164
+
165
+ private calculateFeasibility(content: string): number {
166
+ // Lower feasibility for very abstract ideas
167
+ const abstractTerms = ['quantum', 'neural', 'blockchain', 'revolutionary', 'paradigm'];
168
+ const abstractCount = abstractTerms.filter(term =>
169
+ content.toLowerCase().includes(term)
170
+ ).length;
171
+
172
+ return Math.max(0.3, 0.9 - abstractCount * 0.1);
173
+ }
174
+
175
+ private calculateImpact(content: string): number {
176
+ // Higher impact for ideas addressing broad audiences or major problems
177
+ const impactIndicators = ['global', 'scalable', 'transform', 'revolutionary', 'fundamental'];
178
+ const matches = impactIndicators.filter(ind =>
179
+ content.toLowerCase().includes(ind)
180
+ ).length;
181
+
182
+ return Math.min(0.95, 0.5 + matches * 0.1);
183
+ }
184
+
185
+ private extractTags(content: string): string[] {
186
+ return content
187
+ .toLowerCase()
188
+ .match(/\b\w{5,}\b/g)
189
+ ?.filter((w, i, arr) => arr.indexOf(w) === i)
190
+ ?.slice(0, 5) || [];
191
+ }
192
+ }
193
+
194
+ // ============================================================================
195
+ // MIND MAPPING ENGINE
196
+ // ============================================================================
197
+
198
+ interface MindMapNode {
199
+ id: string;
200
+ label: string;
201
+ children: MindMapNode[];
202
+ connections: string[];
203
+ }
204
+
205
+ class MindMappingEngine {
206
+ createMindMap(centerConcept: string, depth: number = 3): MindMapNode {
207
+ const root: MindMapNode = {
208
+ id: 'root',
209
+ label: centerConcept,
210
+ children: [],
211
+ connections: []
212
+ };
213
+
214
+ this.expandNode(root, depth, 0);
215
+ return root;
216
+ }
217
+
218
+ private expandNode(node: MindMapNode, maxDepth: number, currentDepth: number): void {
219
+ if (currentDepth >= maxDepth) return;
220
+
221
+ const branches = this.generateBranches(node.label, currentDepth);
222
+
223
+ branches.forEach(branchLabel => {
224
+ const child: MindMapNode = {
225
+ id: `node_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`,
226
+ label: branchLabel,
227
+ children: [],
228
+ connections: []
229
+ };
230
+
231
+ node.children.push(child);
232
+ this.expandNode(child, maxDepth, currentDepth + 1);
233
+ });
234
+ }
235
+
236
+ private generateBranches(concept: string, depth: number): string[] {
237
+ const branchTypes: Record<number, string[][]> = {
238
+ 0: [['What', 'Why', 'How', 'When', 'Where']],
239
+ 1: [['Components', 'Features', 'Benefits', 'Challenges']],
240
+ 2: [['Examples', 'Alternatives', 'Applications', 'Implications']]
241
+ };
242
+
243
+ const branches = branchTypes[depth] || [['Details', 'Related', 'Future']];
244
+ const selectedBranch = branches[0];
245
+
246
+ return selectedBranch.map(b => `${b} of ${concept}`);
247
+ }
248
+
249
+ findConnections(node1: MindMapNode, node2: MindMapNode): string[] {
250
+ const connections: string[] = [];
251
+ const concepts1 = this.extractAllConcepts(node1);
252
+ const concepts2 = this.extractAllConcepts(node2);
253
+
254
+ concepts1.forEach(c1 => {
255
+ concepts2.forEach(c2 => {
256
+ const similarity = this.calculateConceptSimilarity(c1, c2);
257
+ if (similarity > 0.5) {
258
+ connections.push(`Connection: ${c1} ↔ ${c2}`);
259
+ }
260
+ });
261
+ });
262
+
263
+ return connections;
264
+ }
265
+
266
+ private extractAllConcepts(node: MindMapNode): string[] {
267
+ const concepts = [node.label];
268
+ node.children.forEach(child => {
269
+ concepts.push(...this.extractAllConcepts(child));
270
+ });
271
+ return concepts;
272
+ }
273
+
274
+ private calculateConceptSimilarity(c1: string, c2: string): number {
275
+ const words1 = c1.toLowerCase().split(/\s+/);
276
+ const words2 = c2.toLowerCase().split(/\s+/);
277
+
278
+ const intersection = words1.filter(w => words2.includes(w));
279
+ return intersection.length / Math.max(words1.length, words2.length);
280
+ }
281
+ }
282
+
283
+ // ============================================================================
284
+ // SCAMPER TECHNIQUE
285
+ // ============================================================================
286
+
287
+ interface ScamperPrompt {
288
+ letter: string;
289
+ action: string;
290
+ prompt: string;
291
+ }
292
+
293
+ class ScamperEngine {
294
+ private scamperPrompts: ScamperPrompt[] = [
295
+ { letter: 'S', action: 'Substitute', prompt: 'What can be substituted?' },
296
+ { letter: 'C', action: 'Combine', prompt: 'What can be combined?' },
297
+ { letter: 'A', action: 'Adapt', prompt: 'What can be adapted?' },
298
+ { letter: 'M', action: 'Modify', prompt: 'What can be modified?' },
299
+ { letter: 'P', action: 'Put to other uses', prompt: 'What other uses are possible?' },
300
+ { letter: 'E', action: 'Eliminate', prompt: 'What can be eliminated?' },
301
+ { letter: 'R', action: 'Reverse/Rearrange', prompt: 'What can be reversed or rearranged?' }
302
+ ];
303
+
304
+ apply(problem: string): Array<{ technique: string; question: string; idea: string }> {
305
+ return this.scamperPrompts.map(prompt => ({
306
+ technique: `${prompt.letter} - ${prompt.action}`,
307
+ question: prompt.prompt,
308
+ idea: this.generateScamperIdea(problem, prompt)
309
+ }));
310
+ }
311
+
312
+ private generateScamperIdea(problem: string, prompt: ScamperPrompt): string {
313
+ const ideaTemplates: Record<string, string[]> = {
314
+ 'Substitute': [
315
+ `Replace a key component of ${problem} with something unexpected`,
316
+ `Use alternative materials or methods for ${problem}`
317
+ ],
318
+ 'Combine': [
319
+ `Merge ${problem} with a completely different concept`,
320
+ `Integrate multiple versions of ${problem}`
321
+ ],
322
+ 'Adapt': [
323
+ `Apply ${problem} in a different context`,
324
+ `Borrow ideas from other fields for ${problem}`
325
+ ],
326
+ 'Modify': [
327
+ `Change the scale or magnitude of ${problem}`,
328
+ `Alter the attributes of ${problem}`
329
+ ],
330
+ 'Put to other uses': [
331
+ `How else could ${problem} be used?`,
332
+ `Who else could benefit from ${problem}?`
333
+ ],
334
+ 'Eliminate': [
335
+ `Remove unnecessary parts of ${problem}`,
336
+ `Simplify ${problem} to its essence`
337
+ ],
338
+ 'Reverse/Rearrange': [
339
+ `Do the opposite of ${problem}`,
340
+ `Change the order of steps in ${problem}`
341
+ ]
342
+ };
343
+
344
+ const templates = ideaTemplates[prompt.action] || ['Consider a new approach'];
345
+ return templates[Math.floor(Math.random() * templates.length)];
346
+ }
347
+ }
348
+
349
+ // ============================================================================
350
+ // SIX THINKING HATS
351
+ // ============================================================================
352
+
353
+ interface ThinkingHat {
354
+ color: string;
355
+ perspective: string;
356
+ focus: string;
357
+ }
358
+
359
+ class SixThinkingHatsEngine {
360
+ private hats: ThinkingHat[] = [
361
+ { color: 'White', perspective: 'Objective', focus: 'facts and data' },
362
+ { color: 'Red', perspective: 'Emotional', focus: 'feelings and intuition' },
363
+ { color: 'Black', perspective: 'Critical', focus: 'risks and problems' },
364
+ { color: 'Yellow', perspective: 'Optimistic', focus: 'benefits and value' },
365
+ { color: 'Green', perspective: 'Creative', focus: 'new ideas and alternatives' },
366
+ { color: 'Blue', perspective: 'Process', focus: 'overview and control' }
367
+ ];
368
+
369
+ analyze(topic: string): Array<{ hat: string; perspective: string; insights: string[] }> {
370
+ return this.hats.map(hat => ({
371
+ hat: hat.color,
372
+ perspective: hat.perspective,
373
+ insights: this.generateInsights(topic, hat)
374
+ }));
375
+ }
376
+
377
+ private generateInsights(topic: string, hat: ThinkingHat): string[] {
378
+ const insights: string[] = [];
379
+
380
+ switch (hat.color) {
381
+ case 'White':
382
+ insights.push(
383
+ `What data do we have about ${topic}?`,
384
+ `What information is missing about ${topic}?`,
385
+ `What are the verifiable facts?`
386
+ );
387
+ break;
388
+ case 'Red':
389
+ insights.push(
390
+ `What is my gut feeling about ${topic}?`,
391
+ `What emotions does ${topic} evoke?`,
392
+ `What is my intuitive reaction?`
393
+ );
394
+ break;
395
+ case 'Black':
396
+ insights.push(
397
+ `What are the risks with ${topic}?`,
398
+ `What could go wrong with ${topic}?`,
399
+ `What are the potential problems?`
400
+ );
401
+ break;
402
+ case 'Yellow':
403
+ insights.push(
404
+ `What are the benefits of ${topic}?`,
405
+ `What value does ${topic} provide?`,
406
+ `What are the opportunities?`
407
+ );
408
+ break;
409
+ case 'Green':
410
+ insights.push(
411
+ `What creative alternatives exist for ${topic}?`,
412
+ `What new ideas can we generate?`,
413
+ `How can we think differently about this?`
414
+ );
415
+ break;
416
+ case 'Blue':
417
+ insights.push(
418
+ `What is our process for addressing ${topic}?`,
419
+ `How should we organize our thinking?`,
420
+ `What is the big picture?`
421
+ );
422
+ break;
423
+ }
424
+
425
+ return insights;
426
+ }
427
+ }
428
+
429
+ // ============================================================================
430
+ // CONCEPT CONNECTOR
431
+ // ============================================================================
432
+
433
+ class ConceptConnector {
434
+ private conceptDatabase: Map<string, string[]> = new Map([
435
+ ['innovation', ['change', 'progress', 'novelty', 'improvement', 'disruption']],
436
+ ['technology', ['tools', 'systems', 'automation', 'digital', 'advancement']],
437
+ ['design', ['aesthetics', 'function', 'user', 'experience', 'form']],
438
+ ['business', ['value', 'profit', 'market', 'customers', 'growth']],
439
+ ['sustainability', ['environment', 'future', 'resources', 'balance', 'responsibility']]
440
+ ]);
441
+
442
+ findConnections(concepts: string[]): Connection[] {
443
+ const connections: Connection[] = [];
444
+
445
+ for (let i = 0; i < concepts.length; i++) {
446
+ for (let j = i + 1; j < concepts.length; j++) {
447
+ const connection = this.analyzeConnection(concepts[i], concepts[j]);
448
+ if (connection.strength > 0.3) {
449
+ connections.push(connection);
450
+ }
451
+ }
452
+ }
453
+
454
+ return connections.sort((a, b) => b.strength - a.strength);
455
+ }
456
+
457
+ private analyzeConnection(concept1: string, concept2: string): Connection {
458
+ const attributes1 = this.getConceptAttributes(concept1);
459
+ const attributes2 = this.getConceptAttributes(concept2);
460
+
461
+ // Find common attributes
462
+ const common = attributes1.filter(a => attributes2.includes(a));
463
+ const all = [...new Set([...attributes1, ...attributes2])];
464
+
465
+ const strength = common.length / all.length;
466
+
467
+ // Determine connection type
468
+ let connectionType: Connection['connectionType'] = 'similarity';
469
+
470
+ if (strength > 0.7) {
471
+ connectionType = 'similarity';
472
+ } else if (strength < 0.3) {
473
+ connectionType = 'contrast';
474
+ } else {
475
+ connectionType = 'combination';
476
+ }
477
+
478
+ return {
479
+ id: `conn_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`,
480
+ from: concept1,
481
+ to: concept2,
482
+ connectionType,
483
+ strength,
484
+ insight: this.generateInsight(concept1, concept2, common, connectionType)
485
+ };
486
+ }
487
+
488
+ private getConceptAttributes(concept: string): string[] {
489
+ const lowerConcept = concept.toLowerCase();
490
+
491
+ for (const [key, attributes] of this.conceptDatabase.entries()) {
492
+ if (lowerConcept.includes(key) || key.includes(lowerConcept)) {
493
+ return attributes;
494
+ }
495
+ }
496
+
497
+ // Generate attributes from concept itself
498
+ return concept.toLowerCase().split(/\s+/).filter(w => w.length > 3);
499
+ }
500
+
501
+ private generateInsight(
502
+ c1: string,
503
+ c2: string,
504
+ common: string[],
505
+ type: Connection['connectionType']
506
+ ): string {
507
+ switch (type) {
508
+ case 'similarity':
509
+ return `${c1} and ${c2} share ${common.length > 0 ? `common ground in ${common.join(', ')}` : 'fundamental similarities'}`;
510
+ case 'contrast':
511
+ return `${c1} and ${c2} represent different approaches that could complement each other`;
512
+ case 'combination':
513
+ return `Combining ${c1} with ${c2} could create something unique`;
514
+ default:
515
+ return `Interesting relationship between ${c1} and ${c2}`;
516
+ }
517
+ }
518
+
519
+ generateNovelCombinations(concepts: string[], count: number = 3): string[] {
520
+ const combinations: string[] = [];
521
+
522
+ for (let i = 0; i < count; i++) {
523
+ const c1 = concepts[Math.floor(Math.random() * concepts.length)];
524
+ const c2 = concepts[Math.floor(Math.random() * concepts.length)];
525
+
526
+ if (c1 !== c2) {
527
+ combinations.push(`Combine ${c1} with ${c2} to create: ${this.generateCombinationName(c1, c2)}`);
528
+ }
529
+ }
530
+
531
+ return combinations;
532
+ }
533
+
534
+ private generateCombinationName(c1: string, c2: string): string {
535
+ const prefixes = ['Smart', 'Dynamic', 'Integrated', 'Adaptive', 'Holistic'];
536
+ const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
537
+ return `${prefix} ${c1.split(' ')[0]}-${c2.split(' ')[0]} Solution`;
538
+ }
539
+ }
540
+
541
+ // ============================================================================
542
+ // OUT-OF-BOX THINKING ENGINE
543
+ // ============================================================================
544
+
545
+ class OutOfBoxEngine {
546
+ private perspectives = [
547
+ 'Beginner\'s mind - forget what you know',
548
+ 'Child\'s perspective - simple and curious',
549
+ 'Alien perspective - no assumptions',
550
+ 'Future perspective - 50 years ahead',
551
+ 'Resource-constrained - extreme limitations',
552
+ 'Opposite approach - do the reverse',
553
+ 'Nature-inspired - biomimicry',
554
+ 'Artistic perspective - beauty and emotion'
555
+ ];
556
+
557
+ reframe(problem: string): OutOfBoxThinking {
558
+ const reframedProblems: ReframedProblem[] = [];
559
+
560
+ this.perspectives.forEach((perspective, index) => {
561
+ const reframed = this.reframeFromPerspective(problem, perspective);
562
+ reframedProblems.push({
563
+ id: `reframe_${Date.now()}_${index}`,
564
+ perspective,
565
+ reframedStatement: reframed.statement,
566
+ assumptionsChallenged: reframed.assumptions,
567
+ newPossibilities: reframed.possibilities
568
+ });
569
+ });
570
+
571
+ const unconventionalApproaches = this.generateUnconventionalApproaches(problem);
572
+ const breakthroughPotential = this.calculateBreakthroughPotential(reframedProblems);
573
+
574
+ return {
575
+ id: `ootb_${Date.now()}`,
576
+ originalProblem: problem,
577
+ reframedProblems,
578
+ unconventionalApproaches,
579
+ breakthroughPotential
580
+ };
581
+ }
582
+
583
+ private reframeFromPerspective(
584
+ problem: string,
585
+ perspective: string
586
+ ): { statement: string; assumptions: string[]; possibilities: string[] } {
587
+ const reframes: Record<string, { statement: string; assumptions: string[]; possibilities: string[] }> = {
588
+ 'Beginner\'s mind': {
589
+ statement: `If you knew nothing about this, how would you approach: ${problem}?`,
590
+ assumptions: ['Expert knowledge is necessary', 'Current methods are optimal'],
591
+ possibilities: ['Fresh approaches', 'Questioning fundamentals']
592
+ },
593
+ 'Child\'s perspective': {
594
+ statement: `How would a 5-year-old solve: ${problem}?`,
595
+ assumptions: ['Complexity is required', 'Adult approaches are better'],
596
+ possibilities: ['Simple solutions', 'Playful approaches']
597
+ },
598
+ 'Alien perspective': {
599
+ statement: `How would beings from another planet view: ${problem}?`,
600
+ assumptions: ['Human perspective is universal', 'Our constraints are absolute'],
601
+ possibilities: ['Radically different approaches', 'Question all assumptions']
602
+ },
603
+ 'Future perspective': {
604
+ statement: `How will people in 2074 solve: ${problem}?`,
605
+ assumptions: ['Current technology limits', 'Present constraints are permanent'],
606
+ possibilities: ['Future technologies', 'Long-term thinking']
607
+ },
608
+ 'Resource-constrained': {
609
+ statement: `How would you solve ${problem} with 1% of current resources?`,
610
+ assumptions: ['Adequate resources are needed', 'Scale is important'],
611
+ possibilities: ['Minimalist solutions', 'Extreme efficiency']
612
+ },
613
+ 'Opposite approach': {
614
+ statement: `What if the solution to ${problem} is the exact opposite of what we think?`,
615
+ assumptions: ['Our direction is correct', 'Conventional wisdom applies'],
616
+ possibilities: ['Counter-intuitive solutions', 'Paradigm shifts']
617
+ },
618
+ 'Nature-inspired': {
619
+ statement: `How does nature solve problems similar to ${problem}?`,
620
+ assumptions: ['Human-designed solutions are superior', 'Technology is the answer'],
621
+ possibilities: ['Biomimicry', 'Natural patterns']
622
+ },
623
+ 'Artistic perspective': {
624
+ statement: `How would an artist approach ${problem}?`,
625
+ assumptions: ['Technical solutions only', 'Function over form'],
626
+ possibilities: ['Aesthetic solutions', 'Emotional design']
627
+ }
628
+ };
629
+
630
+ return reframes[perspective] || {
631
+ statement: `Reframe: ${problem}`,
632
+ assumptions: ['Standard approach'],
633
+ possibilities: ['Alternative approaches']
634
+ };
635
+ }
636
+
637
+ private generateUnconventionalApproaches(problem: string): string[] {
638
+ return [
639
+ `What if ${problem} is actually an opportunity in disguise?`,
640
+ `How can ${problem} be made worse, then reverse that?`,
641
+ `What would make ${problem} solve itself?`,
642
+ `Who benefits from ${problem} existing?`,
643
+ `What if the problem and solution are the same thing?`
644
+ ];
645
+ }
646
+
647
+ private calculateBreakthroughPotential(reframedProblems: ReframedProblem[]): number {
648
+ const totalAssumptions = reframedProblems.reduce(
649
+ (sum, rp) => sum + rp.assumptionsChallenged.length,
650
+ 0
651
+ );
652
+ const totalPossibilities = reframedProblems.reduce(
653
+ (sum, rp) => sum + rp.newPossibilities.length,
654
+ 0
655
+ );
656
+
657
+ return Math.min(0.95, (totalAssumptions * 0.05 + totalPossibilities * 0.1));
658
+ }
659
+ }
660
+
661
+ // ============================================================================
662
+ // MAIN CREATIVITY ENGINE
663
+ // ============================================================================
664
+
665
+ export class CreativityEngine extends EventEmitter {
666
+ private brainstormingEngine: BrainstormingEngine;
667
+ private mindMappingEngine: MindMappingEngine;
668
+ private scamperEngine: ScamperEngine;
669
+ private sixHatsEngine: SixThinkingHatsEngine;
670
+ private conceptConnector: ConceptConnector;
671
+ private outOfBoxEngine: OutOfBoxEngine;
672
+ private sessions: Map<string, CreativeSession> = new Map();
673
+
674
+ constructor() {
675
+ super();
676
+ this.brainstormingEngine = new BrainstormingEngine();
677
+ this.mindMappingEngine = new MindMappingEngine();
678
+ this.scamperEngine = new ScamperEngine();
679
+ this.sixHatsEngine = new SixThinkingHatsEngine();
680
+ this.conceptConnector = new ConceptConnector();
681
+ this.outOfBoxEngine = new OutOfBoxEngine();
682
+ }
683
+
684
+ /**
685
+ * Start a creative session
686
+ */
687
+ startSession(
688
+ prompt: string,
689
+ options: {
690
+ techniques?: CreativityTechnique[];
691
+ ideaCount?: number;
692
+ duration?: number;
693
+ } = {}
694
+ ): CreativeSession {
695
+ const {
696
+ techniques = ['brainstorming', 'analogy', 'scamper'],
697
+ ideaCount = 15,
698
+ duration = 30
699
+ } = options;
700
+
701
+ const sessionId = this.generateId();
702
+ const startTime = Date.now();
703
+
704
+ this.emit('creativity_start', {
705
+ id: sessionId,
706
+ stage: ThinkingStage.CREATIVITY,
707
+ timestamp: new Date(),
708
+ data: { prompt, techniques }
709
+ } as ThinkingEvent);
710
+
711
+ // Generate ideas using specified techniques
712
+ const ideas: Idea[] = [];
713
+
714
+ techniques.forEach(technique => {
715
+ const techniqueIdeas = this.generateIdeasWithTechnique(prompt, technique, Math.ceil(ideaCount / techniques.length));
716
+ ideas.push(...techniqueIdeas);
717
+ });
718
+
719
+ // Find connections between ideas
720
+ const connections = this.findConnections(ideas);
721
+
722
+ // Divergent phase
723
+ const divergentPhase: DivergentPhase = {
724
+ startTime: new Date(startTime),
725
+ endTime: new Date(),
726
+ ideaCount: ideas.length,
727
+ explorationBreadth: techniques.length
728
+ };
729
+
730
+ // Convergent phase - select best ideas
731
+ const selectedIdeas = this.selectBestIdeas(ideas, 5);
732
+ const synthesis = this.synthesizeIdeas(selectedIdeas);
733
+
734
+ const convergentPhase: ConvergentPhase = {
735
+ startTime: new Date(),
736
+ endTime: new Date(),
737
+ selectedIdeas: selectedIdeas.map(i => i.id),
738
+ synthesis,
739
+ actionItems: this.generateActionItems(selectedIdeas)
740
+ };
741
+
742
+ const session: CreativeSession = {
743
+ id: sessionId,
744
+ prompt,
745
+ techniques,
746
+ ideas,
747
+ connections,
748
+ sessionDuration: Date.now() - startTime,
749
+ divergentPhase,
750
+ convergentPhase
751
+ };
752
+
753
+ this.sessions.set(sessionId, session);
754
+
755
+ this.emit('creativity_complete', {
756
+ id: sessionId,
757
+ stage: ThinkingStage.CREATIVITY,
758
+ timestamp: new Date(),
759
+ data: {
760
+ ideaCount: ideas.length,
761
+ connectionCount: connections.length,
762
+ topIdeas: selectedIdeas.map(i => i.content.substring(0, 50))
763
+ }
764
+ } as ThinkingEvent);
765
+
766
+ return session;
767
+ }
768
+
769
+ /**
770
+ * Generate ideas using a specific technique
771
+ */
772
+ private generateIdeasWithTechnique(
773
+ prompt: string,
774
+ technique: CreativityTechnique,
775
+ count: number
776
+ ): Idea[] {
777
+ switch (technique) {
778
+ case 'brainstorming':
779
+ case 'analogy':
780
+ case 'reverse_thinking':
781
+ case 'random_stimulus':
782
+ case 'lateral_thinking':
783
+ return this.brainstormingEngine.generateIdeas(prompt, count);
784
+ case 'scamper':
785
+ return this.applyScamperInternal(prompt);
786
+ case 'mind_mapping':
787
+ return this.generateFromMindMap(prompt, count);
788
+ case 'six_thinking_hats':
789
+ return this.applySixHatsInternal(prompt);
790
+ default:
791
+ return this.brainstormingEngine.generateIdeas(prompt, count);
792
+ }
793
+ }
794
+
795
+ private applyScamperInternal(prompt: string): Idea[] {
796
+ const scamperResults = this.scamperEngine.apply(prompt);
797
+ return scamperResults.map((result, index) => ({
798
+ id: `idea_scamper_${Date.now()}_${index}`,
799
+ content: `${result.technique}: ${result.idea}`,
800
+ technique: 'scamper',
801
+ novelty: 0.7,
802
+ feasibility: 0.6,
803
+ impact: 0.65,
804
+ relatedIdeas: [],
805
+ tags: ['scamper', result.technique.toLowerCase()],
806
+ generatedAt: new Date()
807
+ }));
808
+ }
809
+
810
+ private generateFromMindMap(prompt: string, count: number): Idea[] {
811
+ const mindMap = this.mindMappingEngine.createMindMap(prompt, 2);
812
+ const ideas: Idea[] = [];
813
+
814
+ const extractIdeas = (node: any, depth: number) => {
815
+ if (ideas.length >= count) return;
816
+
817
+ ideas.push({
818
+ id: `idea_mindmap_${Date.now()}_${ideas.length}`,
819
+ content: `Explore: ${node.label}`,
820
+ technique: 'mind_mapping',
821
+ novelty: 0.6 + depth * 0.1,
822
+ feasibility: 0.7,
823
+ impact: 0.6,
824
+ relatedIdeas: [],
825
+ tags: ['mindmap', `level_${depth}`],
826
+ generatedAt: new Date()
827
+ });
828
+
829
+ node.children.forEach((child: any) => extractIdeas(child, depth + 1));
830
+ };
831
+
832
+ extractIdeas(mindMap, 0);
833
+ return ideas.slice(0, count);
834
+ }
835
+
836
+ private applySixHatsInternal(prompt: string): Idea[] {
837
+ const hatsResults = this.sixHatsEngine.analyze(prompt);
838
+ return hatsResults.map((result, index) => ({
839
+ id: `idea_hat_${Date.now()}_${index}`,
840
+ content: `${result.hat} Hat perspective: ${result.insights[0]}`,
841
+ technique: 'six_thinking_hats',
842
+ novelty: 0.65,
843
+ feasibility: 0.75,
844
+ impact: 0.7,
845
+ relatedIdeas: [],
846
+ tags: ['six_hats', result.hat.toLowerCase()],
847
+ generatedAt: new Date()
848
+ }));
849
+ }
850
+
851
+ /**
852
+ * Find connections between ideas
853
+ */
854
+ private findConnections(ideas: Idea[]): Connection[] {
855
+ const concepts = ideas.map(i => i.content);
856
+ return this.conceptConnector.findConnections(concepts);
857
+ }
858
+
859
+ /**
860
+ * Select best ideas based on multiple criteria
861
+ */
862
+ private selectBestIdeas(ideas: Idea[], count: number): Idea[] {
863
+ return ideas
864
+ .map(idea => ({
865
+ idea,
866
+ score: idea.novelty * 0.3 + idea.feasibility * 0.4 + idea.impact * 0.3
867
+ }))
868
+ .sort((a, b) => b.score - a.score)
869
+ .slice(0, count)
870
+ .map(({ idea }) => idea);
871
+ }
872
+
873
+ /**
874
+ * Synthesize selected ideas into coherent concept
875
+ */
876
+ private synthesizeIdeas(ideas: Idea[]): string {
877
+ const themes = this.extractCommonThemes(ideas);
878
+ return `Synthesis: Combining ${ideas.length} ideas reveals ${themes.length} key themes: ` +
879
+ `${themes.join(', ')}. The integrated solution leverages the strengths of each approach.`;
880
+ }
881
+
882
+ private extractCommonThemes(ideas: Idea[]): string[] {
883
+ const allTags = ideas.flatMap(i => i.tags);
884
+ const tagFreq = new Map<string, number>();
885
+
886
+ allTags.forEach(tag => {
887
+ tagFreq.set(tag, (tagFreq.get(tag) || 0) + 1);
888
+ });
889
+
890
+ return Array.from(tagFreq.entries())
891
+ .sort((a, b) => b[1] - a[1])
892
+ .slice(0, 3)
893
+ .map(([tag]) => tag);
894
+ }
895
+
896
+ private generateActionItems(ideas: Idea[]): string[] {
897
+ return ideas.slice(0, 3).map((idea, index) =>
898
+ `${index + 1}. Explore: ${idea.content.substring(0, 50)}...`
899
+ );
900
+ }
901
+
902
+ /**
903
+ * Apply out-of-box thinking to a problem
904
+ */
905
+ thinkOutOfBox(problem: string): OutOfBoxThinking {
906
+ return this.outOfBoxEngine.reframe(problem);
907
+ }
908
+
909
+ /**
910
+ * Generate novel combinations of concepts
911
+ */
912
+ generateCombinations(concepts: string[], count?: number): string[] {
913
+ return this.conceptConnector.generateNovelCombinations(concepts, count);
914
+ }
915
+
916
+ /**
917
+ * Create mind map
918
+ */
919
+ createMindMap(centerConcept: string, depth?: number): any {
920
+ return this.mindMappingEngine.createMindMap(centerConcept, depth);
921
+ }
922
+
923
+ /**
924
+ * Apply SCAMPER technique
925
+ */
926
+ applyScamper(problem: string): Array<{ technique: string; question: string; idea: string }> {
927
+ return this.scamperEngine.apply(problem);
928
+ }
929
+
930
+ /**
931
+ * Apply Six Thinking Hats
932
+ */
933
+ applySixHats(topic: string): Array<{ hat: string; perspective: string; insights: string[] }> {
934
+ return this.sixHatsEngine.analyze(topic);
935
+ }
936
+
937
+ /**
938
+ * Get creative session
939
+ */
940
+ getSession(sessionId: string): CreativeSession | undefined {
941
+ return this.sessions.get(sessionId);
942
+ }
943
+
944
+ private generateId(): string {
945
+ return `creative_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
946
+ }
947
+ }
948
+
949
+ // ============================================================================
950
+ // EXPORT SINGLETON INSTANCE
951
+ // ============================================================================
952
+
953
+ export const creativityEngine = new CreativityEngine();
954
+
955
+ // ============================================================================
956
+ // EXAMPLE USAGE
957
+ // ============================================================================
958
+
959
+ /*
960
+ // Start a creative session
961
+ const session = creativityEngine.startSession(
962
+ 'How can we improve remote team collaboration?',
963
+ {
964
+ techniques: ['brainstorming', 'scamper', 'six_thinking_hats'],
965
+ ideaCount: 20
966
+ }
967
+ );
968
+
969
+ // Out-of-box thinking
970
+ const outOfBox = creativityEngine.thinkOutOfBox(
971
+ 'Our product has low user engagement'
972
+ );
973
+
974
+ // Generate combinations
975
+ const combinations = creativityEngine.generateCombinations(
976
+ ['AI', 'collaboration', 'gamification', 'VR'],
977
+ 5
978
+ );
979
+
980
+ // Create mind map
981
+ const mindMap = creativityEngine.createMindMap('Innovation Strategy', 3);
982
+
983
+ // Apply SCAMPER
984
+ const scamperResults = creativityEngine.applyScamper(
985
+ 'Traditional education system'
986
+ );
987
+
988
+ // Apply Six Thinking Hats
989
+ const hatsAnalysis = creativityEngine.applySixHats(
990
+ 'Implementing AI in healthcare'
991
+ );
992
+
993
+ // Access generated ideas
994
+ const topIdeas = session.ideas
995
+ .sort((a, b) => (b.novelty + b.feasibility + b.impact) - (a.novelty + a.feasibility + a.impact))
996
+ .slice(0, 5);
997
+
998
+ // Get connections between ideas
999
+ const connections = session.connections
1000
+ .filter(c => c.strength > 0.5)
1001
+ .slice(0, 3);
1002
+ */