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/reasoning.ts DELETED
@@ -1,1079 +0,0 @@
1
- /**
2
- * Reasoning Module
3
- * Advanced logical reasoning with Chain of Thought, hypothesis testing, and multi-step problem solving
4
- */
5
-
6
- import {
7
- ReasoningSession,
8
- ReasoningStep,
9
- ReasoningType,
10
- Hypothesis,
11
- HypothesisTest,
12
- ChainOfThought,
13
- ThoughtNode,
14
- ProblemDecomposition,
15
- SubProblem,
16
- Dependency,
17
- Evidence,
18
- TaskStatus,
19
- ThinkingEvent,
20
- ThinkingError,
21
- ThinkingStage
22
- } from './types';
23
- import { EventEmitter } from 'events';
24
- import { llmService } from './llm-service';
25
-
26
- // ============================================================================
27
- // LOGICAL RULES ENGINE
28
- // ============================================================================
29
-
30
- interface Rule {
31
- id: string;
32
- premises: string[];
33
- conclusion: string;
34
- confidence: number;
35
- domain: string;
36
- }
37
-
38
- class LogicalRulesEngine {
39
- private rules: Map<string, Rule> = new Map();
40
-
41
- addRule(rule: Rule): void {
42
- this.rules.set(rule.id, rule);
43
- }
44
-
45
- infer(facts: string[]): Array<{ conclusion: string; confidence: number; rule: Rule }> {
46
- const inferences: Array<{ conclusion: string; confidence: number; rule: Rule }> = [];
47
-
48
- this.rules.forEach(rule => {
49
- const premisesMet = rule.premises.every(premise =>
50
- facts.some(fact => this.match(fact, premise))
51
- );
52
-
53
- if (premisesMet) {
54
- inferences.push({
55
- conclusion: rule.conclusion,
56
- confidence: rule.confidence,
57
- rule
58
- });
59
- }
60
- });
61
-
62
- return inferences.sort((a, b) => b.confidence - a.confidence);
63
- }
64
-
65
- private match(fact: string, premise: string): boolean {
66
- // Simple pattern matching - in real implementation use NLP
67
- const factWords = fact.toLowerCase().split(/\s+/);
68
- const premiseWords = premise.toLowerCase().split(/\s+/);
69
-
70
- const matchCount = premiseWords.filter(pw =>
71
- factWords.some(fw => fw.includes(pw) || pw.includes(fw))
72
- ).length;
73
-
74
- return matchCount / premiseWords.length > 0.7;
75
- }
76
-
77
- getRulesByDomain(domain: string): Rule[] {
78
- return Array.from(this.rules.values()).filter(r => r.domain === domain);
79
- }
80
- }
81
-
82
- // ============================================================================
83
- // CHAIN OF THOUGHT GENERATOR
84
- // ============================================================================
85
-
86
- class ChainOfThoughtGenerator {
87
- private thoughtId = 0;
88
-
89
- generate(question: string, maxDepth: number = 5): ChainOfThought {
90
- const thoughts: ThoughtNode[] = [];
91
- const rootThought: ThoughtNode = {
92
- id: this.nextThoughtId(),
93
- content: question,
94
- children: [],
95
- depth: 0,
96
- confidence: 1.0,
97
- type: 'question'
98
- };
99
- thoughts.push(rootThought);
100
-
101
- // Generate thought chain
102
- this.expandThought(rootThought, thoughts, maxDepth, 0);
103
-
104
- // Generate final answer based on thought chain
105
- const finalAnswer = this.synthesizeAnswer(thoughts);
106
-
107
- return {
108
- id: `cot_${Date.now()}`,
109
- initialQuestion: question,
110
- thoughts,
111
- finalAnswer,
112
- completeness: this.calculateCompleteness(thoughts)
113
- };
114
- }
115
-
116
- private expandThought(
117
- parent: ThoughtNode,
118
- thoughts: ThoughtNode[],
119
- maxDepth: number,
120
- currentDepth: number
121
- ): void {
122
- if (currentDepth >= maxDepth) return;
123
-
124
- const expansions = this.generateExpansions(parent, currentDepth);
125
-
126
- expansions.forEach(expansion => {
127
- const child: ThoughtNode = {
128
- id: this.nextThoughtId(),
129
- content: expansion.content,
130
- parentId: parent.id,
131
- children: [],
132
- depth: currentDepth + 1,
133
- confidence: expansion.confidence * parent.confidence,
134
- type: expansion.type
135
- };
136
-
137
- parent.children.push(child.id);
138
- thoughts.push(child);
139
-
140
- // Recursively expand if it's an observation or inference
141
- if (expansion.type === 'observation' || expansion.type === 'inference') {
142
- this.expandThought(child, thoughts, maxDepth, currentDepth + 1);
143
- }
144
- });
145
- }
146
-
147
- private generateExpansions(thought: ThoughtNode, depth: number): Array<{ content: string; type: ThoughtNode['type']; confidence: number }> {
148
- const expansions: Array<{ content: string; type: ThoughtNode['type']; confidence: number }> = [];
149
- const content = thought.content.toLowerCase();
150
-
151
- // Generate contextual expansions based on thought type
152
- if (thought.type === 'question') {
153
- expansions.push(
154
- { content: `Let me break down this question into parts.`, type: 'observation', confidence: 0.9 },
155
- { content: `What are the key elements involved?`, type: 'observation', confidence: 0.85 },
156
- { content: `What do I already know about this?`, type: 'observation', confidence: 0.8 }
157
- );
158
- } else if (thought.type === 'observation') {
159
- expansions.push(
160
- { content: `This suggests that...`, type: 'inference', confidence: 0.75 },
161
- { content: `One implication is...`, type: 'inference', confidence: 0.7 },
162
- { content: `However, we must also consider...`, type: 'observation', confidence: 0.65 }
163
- );
164
- } else if (thought.type === 'inference') {
165
- if (depth < 3) {
166
- expansions.push(
167
- { content: `Building on this inference...`, type: 'inference', confidence: 0.7 },
168
- { content: `This leads to the conclusion that...`, type: 'conclusion', confidence: 0.8 }
169
- );
170
- } else {
171
- expansions.push(
172
- { content: `Therefore, we can conclude...`, type: 'conclusion', confidence: 0.85 }
173
- );
174
- }
175
- }
176
-
177
- return expansions;
178
- }
179
-
180
- private synthesizeAnswer(thoughts: ThoughtNode[]): string {
181
- const conclusions = thoughts.filter(t => t.type === 'conclusion');
182
- const inferences = thoughts.filter(t => t.type === 'inference');
183
-
184
- if (conclusions.length > 0) {
185
- const topConclusion = conclusions.sort((a, b) => b.confidence - a.confidence)[0];
186
- return topConclusion.content + ' Based on the analysis: ' +
187
- inferences.slice(0, 3).map(i => i.content).join('; ') + '.';
188
- }
189
-
190
- return 'Based on the analysis: ' + inferences.slice(0, 3).map(i => i.content).join('; ') + '.';
191
- }
192
-
193
- private calculateCompleteness(thoughts: ThoughtNode[]): number {
194
- const hasQuestion = thoughts.some(t => t.type === 'question');
195
- const hasObservations = thoughts.some(t => t.type === 'observation');
196
- const hasInferences = thoughts.some(t => t.type === 'inference');
197
- const hasConclusions = thoughts.some(t => t.type === 'conclusion');
198
-
199
- const elements = [hasQuestion, hasObservations, hasInferences, hasConclusions];
200
- return elements.filter(Boolean).length / elements.length;
201
- }
202
-
203
- private nextThoughtId(): string {
204
- return `thought_${++this.thoughtId}`;
205
- }
206
- }
207
-
208
- // ============================================================================
209
- // HYPOTHESIS MANAGER
210
- // ============================================================================
211
-
212
- class HypothesisManager {
213
- private hypotheses: Map<string, Hypothesis> = new Map();
214
-
215
- createHypothesis(statement: string): Hypothesis {
216
- const hypothesis: Hypothesis = {
217
- id: `hypothesis_${Date.now()}`,
218
- statement,
219
- supportingEvidence: [],
220
- contradictingEvidence: [],
221
- tests: [],
222
- status: 'proposed',
223
- confidence: 0.5
224
- };
225
-
226
- this.hypotheses.set(hypothesis.id, hypothesis);
227
- return hypothesis;
228
- }
229
-
230
- addEvidence(hypothesisId: string, evidence: Evidence, supporting: boolean): void {
231
- const hypothesis = this.hypotheses.get(hypothesisId);
232
- if (!hypothesis) throw new Error(`Hypothesis ${hypothesisId} not found`);
233
-
234
- if (supporting) {
235
- hypothesis.supportingEvidence.push(evidence);
236
- } else {
237
- hypothesis.contradictingEvidence.push(evidence);
238
- }
239
-
240
- this.updateConfidence(hypothesis);
241
- }
242
-
243
- addTest(hypothesisId: string, test: HypothesisTest): void {
244
- const hypothesis = this.hypotheses.get(hypothesisId);
245
- if (!hypothesis) throw new Error(`Hypothesis ${hypothesisId} not found`);
246
-
247
- hypothesis.tests.push(test);
248
- }
249
-
250
- runTest(hypothesisId: string, testId: string, outcome: string): void {
251
- const hypothesis = this.hypotheses.get(hypothesisId);
252
- if (!hypothesis) throw new Error(`Hypothesis ${hypothesisId} not found`);
253
-
254
- const test = hypothesis.tests.find(t => t.id === testId);
255
- if (!test) throw new Error(`Test ${testId} not found`);
256
-
257
- test.actualOutcome = outcome;
258
- test.passed = outcome === test.expectedOutcome;
259
-
260
- this.updateStatus(hypothesis);
261
- }
262
-
263
- private updateConfidence(hypothesis: Hypothesis): void {
264
- const supportWeight = hypothesis.supportingEvidence.reduce((sum, e) => sum + e.strength, 0);
265
- const contradictWeight = hypothesis.contradictingEvidence.reduce((sum, e) => sum + e.strength, 0);
266
-
267
- const totalWeight = supportWeight + contradictWeight;
268
- if (totalWeight === 0) {
269
- hypothesis.confidence = 0.5;
270
- } else {
271
- hypothesis.confidence = supportWeight / totalWeight;
272
- }
273
- }
274
-
275
- private updateStatus(hypothesis: Hypothesis): void {
276
- const completedTests = hypothesis.tests.filter(t => t.passed !== undefined);
277
- const passedTests = completedTests.filter(t => t.passed);
278
-
279
- if (completedTests.length === 0) {
280
- hypothesis.status = 'testing';
281
- } else if (passedTests.length === completedTests.length && hypothesis.confidence > 0.8) {
282
- hypothesis.status = 'confirmed';
283
- } else if (passedTests.length === 0 && completedTests.length > 2) {
284
- hypothesis.status = 'rejected';
285
- } else {
286
- hypothesis.status = 'testing';
287
- }
288
- }
289
-
290
- getHypothesis(id: string): Hypothesis | undefined {
291
- return this.hypotheses.get(id);
292
- }
293
-
294
- getAllHypotheses(): Hypothesis[] {
295
- return Array.from(this.hypotheses.values());
296
- }
297
-
298
- getHypothesesByStatus(status: Hypothesis['status']): Hypothesis[] {
299
- return this.getAllHypotheses().filter(h => h.status === status);
300
- }
301
- }
302
-
303
- // ============================================================================
304
- // PROBLEM DECOMPOSITION ENGINE
305
- // ============================================================================
306
-
307
- class ProblemDecompositionEngine {
308
- decompose(problem: string): ProblemDecomposition {
309
- const subProblems: SubProblem[] = [];
310
- const dependencies: Dependency[] = [];
311
-
312
- // Analyze problem structure
313
- const problemParts = this.identifyProblemParts(problem);
314
-
315
- // Create sub-problems
316
- problemParts.forEach((part, index) => {
317
- const subProblem: SubProblem = {
318
- id: `sub_${index}`,
319
- description: part.description,
320
- difficulty: part.difficulty,
321
- estimatedTime: part.estimatedTime,
322
- prerequisites: [],
323
- status: TaskStatus.PENDING
324
- };
325
- subProblems.push(subProblem);
326
- });
327
-
328
- // Identify dependencies
329
- subProblems.forEach((sub, i) => {
330
- subProblems.forEach((other, j) => {
331
- if (i !== j && this.hasDependency(sub, other)) {
332
- dependencies.push({
333
- from: sub.id,
334
- to: other.id,
335
- type: 'requires'
336
- });
337
- sub.prerequisites.push(other.id);
338
- }
339
- });
340
- });
341
-
342
- // Determine solution strategy
343
- const solutionStrategy = this.determineStrategy(subProblems, dependencies);
344
-
345
- return {
346
- id: `decomp_${Date.now()}`,
347
- originalProblem: problem,
348
- subProblems,
349
- dependencies,
350
- solutionStrategy
351
- };
352
- }
353
-
354
- private identifyProblemParts(problem: string): Array<{ description: string; difficulty: number; estimatedTime: number }> {
355
- const parts: Array<{ description: string; difficulty: number; estimatedTime: number }> = [];
356
-
357
- // Simple decomposition based on keywords
358
- const keywords = {
359
- research: { difficulty: 0.7, time: 120 },
360
- analyze: { difficulty: 0.6, time: 90 },
361
- design: { difficulty: 0.8, time: 180 },
362
- implement: { difficulty: 0.75, time: 240 },
363
- test: { difficulty: 0.5, time: 60 },
364
- optimize: { difficulty: 0.85, time: 150 },
365
- evaluate: { difficulty: 0.55, time: 45 },
366
- plan: { difficulty: 0.4, time: 30 }
367
- };
368
-
369
- const problemLower = problem.toLowerCase();
370
-
371
- Object.entries(keywords).forEach(([keyword, config]) => {
372
- if (problemLower.includes(keyword)) {
373
- parts.push({
374
- description: `${keyword.charAt(0).toUpperCase() + keyword.slice(1)} phase of the problem`,
375
- difficulty: config.difficulty,
376
- estimatedTime: config.time
377
- });
378
- }
379
- });
380
-
381
- // If no specific parts identified, create generic ones
382
- if (parts.length === 0) {
383
- parts.push(
384
- { description: 'Understand the problem', difficulty: 0.4, estimatedTime: 30 },
385
- { description: 'Research and gather information', difficulty: 0.6, estimatedTime: 60 },
386
- { description: 'Develop solution approach', difficulty: 0.7, estimatedTime: 90 },
387
- { description: 'Implement the solution', difficulty: 0.75, estimatedTime: 120 },
388
- { description: 'Verify and validate', difficulty: 0.5, estimatedTime: 45 }
389
- );
390
- }
391
-
392
- return parts;
393
- }
394
-
395
- private hasDependency(sub1: SubProblem, sub2: SubProblem): boolean {
396
- // Check if sub1 requires sub2 based on description
397
- const orderIndicators: Record<string, string[]> = {
398
- 'understand': [],
399
- 'research': ['understand'],
400
- 'design': ['research', 'understand'],
401
- 'implement': ['design', 'research'],
402
- 'test': ['implement'],
403
- 'optimize': ['test', 'implement'],
404
- 'evaluate': ['test', 'implement', 'optimize'],
405
- 'plan': ['understand', 'research']
406
- };
407
-
408
- const sub1Keywords = Object.keys(orderIndicators).filter(k =>
409
- sub1.description.toLowerCase().includes(k)
410
- );
411
- const sub2Keywords = Object.keys(orderIndicators).filter(k =>
412
- sub2.description.toLowerCase().includes(k)
413
- );
414
-
415
- return sub1Keywords.some(k1 =>
416
- sub2Keywords.some(k2 => orderIndicators[k1]?.includes(k2))
417
- );
418
- }
419
-
420
- private determineStrategy(subProblems: SubProblem[], dependencies: Dependency[]): string {
421
- const criticalPath = this.findCriticalPath(subProblems, dependencies);
422
- const totalTime = subProblems.reduce((sum, sp) => sum + sp.estimatedTime, 0);
423
- const avgDifficulty = subProblems.reduce((sum, sp) => sum + sp.difficulty, 0) / subProblems.length;
424
-
425
- if (avgDifficulty > 0.7) {
426
- return `Divide-and-conquer approach recommended. Tackle critical path first: ${criticalPath.join(' → ')}. Estimated total time: ${totalTime} minutes.`;
427
- } else if (dependencies.length > subProblems.length) {
428
- return `Sequential approach with careful dependency management. Start with: ${criticalPath[0]}.`;
429
- } else {
430
- return `Parallel processing possible. Focus on: ${criticalPath.join(', ')}.`;
431
- }
432
- }
433
-
434
- private findCriticalPath(subProblems: SubProblem[], dependencies: Dependency[]): string[] {
435
- // Simplified critical path - in real implementation use topological sort
436
- const visited = new Set<string>();
437
- const path: string[] = [];
438
-
439
- const visit = (subId: string) => {
440
- if (visited.has(subId)) return;
441
- visited.add(subId);
442
-
443
- const prereqs = dependencies
444
- .filter(d => d.to === subId && d.type === 'requires')
445
- .map(d => d.from);
446
-
447
- prereqs.forEach(visit);
448
-
449
- const sub = subProblems.find(s => s.id === subId);
450
- if (sub) path.push(sub.description);
451
- };
452
-
453
- subProblems.forEach(sp => visit(sp.id));
454
-
455
- return path.length > 0 ? path : subProblems.map(s => s.description);
456
- }
457
- }
458
-
459
- // ============================================================================
460
- // REASONING ENGINE
461
- // ============================================================================
462
-
463
- export class ReasoningEngine extends EventEmitter {
464
- private rulesEngine: LogicalRulesEngine;
465
- private cotGenerator: ChainOfThoughtGenerator;
466
- private hypothesisManager: HypothesisManager;
467
- private decompositionEngine: ProblemDecompositionEngine;
468
- private sessions: Map<string, ReasoningSession> = new Map();
469
-
470
- constructor() {
471
- super();
472
- this.rulesEngine = new LogicalRulesEngine();
473
- this.cotGenerator = new ChainOfThoughtGenerator();
474
- this.hypothesisManager = new HypothesisManager();
475
- this.decompositionEngine = new ProblemDecompositionEngine();
476
- this.initializeDefaultRules();
477
- }
478
-
479
- private initializeDefaultRules(): void {
480
- // Add some default logical rules
481
- this.rulesEngine.addRule({
482
- id: 'rule_cause_effect',
483
- premises: ['A causes B', 'A occurred'],
484
- conclusion: 'B will occur',
485
- confidence: 0.8,
486
- domain: 'causality'
487
- });
488
-
489
- this.rulesEngine.addRule({
490
- id: 'rule_generalization',
491
- premises: ['All X are Y', 'Z is X'],
492
- conclusion: 'Z is Y',
493
- confidence: 0.95,
494
- domain: 'logic'
495
- });
496
-
497
- this.rulesEngine.addRule({
498
- id: 'rule_analogy',
499
- premises: ['A is similar to B', 'A has property P'],
500
- conclusion: 'B likely has property P',
501
- confidence: 0.7,
502
- domain: 'analogy'
503
- });
504
- }
505
-
506
- /**
507
- * Perform reasoning on a problem
508
- */
509
- async reason(
510
- problem: string,
511
- options: {
512
- type?: ReasoningType;
513
- maxSteps?: number;
514
- generateCOT?: boolean;
515
- } = {}
516
- ): Promise<ReasoningSession> {
517
- const {
518
- type = ReasoningType.DEDUCTIVE,
519
- maxSteps = 5,
520
- generateCOT = true
521
- } = options;
522
-
523
- const sessionId = this.generateId();
524
- const startTime = Date.now();
525
-
526
- const session: ReasoningSession = {
527
- id: sessionId,
528
- problem,
529
- type,
530
- steps: [],
531
- confidence: 0,
532
- startTime: new Date()
533
- };
534
-
535
- this.sessions.set(sessionId, session);
536
-
537
- this.emit('reasoning_start', {
538
- id: sessionId,
539
- stage: ThinkingStage.REASONING,
540
- timestamp: new Date(),
541
- data: { problem, type }
542
- } as ThinkingEvent);
543
-
544
- try {
545
- // Generate Chain of Thought if enabled (via LLM implicitly or explicitly)
546
- let cot: ChainOfThought | undefined;
547
-
548
- // Try LLM-based reasoning first
549
- await this.executeReasoningWithLLM(session, maxSteps);
550
-
551
- // If LLM failed (empty steps), fallback to internal engines
552
- if (session.steps.length === 0) {
553
- if (generateCOT) {
554
- cot = this.cotGenerator.generate(problem, maxSteps);
555
- }
556
-
557
- switch (type) {
558
- case ReasoningType.DEDUCTIVE:
559
- await this.executeDeductiveReasoning(session, maxSteps);
560
- break;
561
- case ReasoningType.INDUCTIVE:
562
- await this.executeInductiveReasoning(session, maxSteps);
563
- break;
564
- case ReasoningType.ABDUCTIVE:
565
- await this.executeAbductiveReasoning(session, maxSteps);
566
- break;
567
- case ReasoningType.ANALOGICAL:
568
- await this.executeAnalogicalReasoning(session, maxSteps);
569
- break;
570
- case ReasoningType.CAUSAL:
571
- await this.executeCausalReasoning(session, maxSteps);
572
- break;
573
- case ReasoningType.COUNTERFACTUAL:
574
- await this.executeCounterfactualReasoning(session, maxSteps);
575
- break;
576
- }
577
-
578
- // Generate conclusion for fallback
579
- session.conclusion = this.generateConclusion(session, cot);
580
- session.confidence = this.calculateSessionConfidence(session);
581
- }
582
-
583
- session.endTime = new Date();
584
-
585
- this.emit('reasoning_complete', {
586
- id: sessionId,
587
- stage: ThinkingStage.REASONING,
588
- timestamp: new Date(),
589
- data: {
590
- session,
591
- steps: session.steps.length,
592
- confidence: session.confidence
593
- }
594
- } as ThinkingEvent);
595
-
596
- return session;
597
-
598
- } catch (error) {
599
- this.emit('reasoning_error', {
600
- id: sessionId,
601
- stage: ThinkingStage.REASONING,
602
- timestamp: new Date(),
603
- data: { error }
604
- } as ThinkingEvent);
605
-
606
- throw new ThinkingError(
607
- `Reasoning failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
608
- ThinkingStage.REASONING,
609
- true,
610
- error instanceof Error ? error : undefined
611
- );
612
- }
613
- }
614
-
615
- private async executeReasoningWithLLM(session: ReasoningSession, maxSteps: number): Promise<void> {
616
- const prompt = `
617
- You are an expert reasoning engine.
618
- Problem: "${session.problem}"
619
- Task: Perform ${session.type} reasoning with approximately ${maxSteps} steps.
620
-
621
- Return a JSON object with this exact structure (no markdown, just JSON):
622
- {
623
- "steps": [
624
- {
625
- "stepNumber": number,
626
- "premise": "string (the basis for this step)",
627
- "inference": "string (the logical deduction)",
628
- "confidence": number (0.0 to 1.0)
629
- }
630
- ],
631
- "conclusion": "string (final conclusion)",
632
- "overallConfidence": number (0.0 to 1.0)
633
- }
634
- `;
635
-
636
- try {
637
- const response = await llmService.generateText({ prompt });
638
- const jsonMatch = response.match(/\{[\s\S]*\}/);
639
-
640
- if (jsonMatch) {
641
- const result = JSON.parse(jsonMatch[0]);
642
-
643
- if (Array.isArray(result.steps)) {
644
- result.steps.forEach((s: any, i: number) => {
645
- session.steps.push({
646
- id: `step_${i}`,
647
- stepNumber: s.stepNumber || i + 1,
648
- premise: s.premise || '',
649
- inference: s.inference || '',
650
- evidence: [],
651
- assumptions: [],
652
- confidence: s.confidence || 0.8,
653
- nextSteps: []
654
- });
655
- });
656
- }
657
-
658
- session.conclusion = result.conclusion;
659
- session.confidence = result.overallConfidence || 0.8;
660
- }
661
- } catch (error) {
662
- console.warn('LLM reasoning failed, falling back to internal engine', error);
663
- // Fallback handled in caller
664
- }
665
- }
666
-
667
- private async executeDeductiveReasoning(session: ReasoningSession, maxSteps: number): Promise<void> {
668
- const facts = this.extractFacts(session.problem);
669
-
670
- for (let i = 0; i < maxSteps; i++) {
671
- const inferences = this.rulesEngine.infer(facts);
672
-
673
- if (inferences.length === 0) break;
674
-
675
- const topInference = inferences[0];
676
-
677
- const step: ReasoningStep = {
678
- id: `step_${i}`,
679
- stepNumber: i + 1,
680
- premise: facts.join(', '),
681
- inference: topInference.conclusion,
682
- evidence: [{
683
- source: 'logical_rules',
684
- excerpt: `Rule: ${topInference.rule.premises.join(' AND ')} => ${topInference.rule.conclusion}`,
685
- location: 'rules_engine',
686
- strength: topInference.confidence
687
- }],
688
- assumptions: topInference.rule.premises,
689
- confidence: topInference.confidence,
690
- nextSteps: inferences.slice(1).map(inf => inf.conclusion)
691
- };
692
-
693
- session.steps.push(step);
694
- facts.push(topInference.conclusion);
695
- }
696
- }
697
-
698
- private async executeInductiveReasoning(session: ReasoningSession, maxSteps: number): Promise<void> {
699
- // Pattern-based reasoning from specific to general
700
- const observations = this.extractObservations(session.problem);
701
-
702
- for (let i = 0; i < maxSteps && i < observations.length; i++) {
703
- const pattern = this.identifyPattern(observations.slice(0, i + 1));
704
-
705
- const step: ReasoningStep = {
706
- id: `step_${i}`,
707
- stepNumber: i + 1,
708
- premise: observations.slice(0, i + 1).join('; '),
709
- inference: `Pattern identified: ${pattern.description}`,
710
- evidence: observations.map(obs => ({
711
- source: 'observation',
712
- excerpt: obs,
713
- location: 'problem_statement',
714
- strength: 0.7
715
- })),
716
- assumptions: ['Observations are representative', 'Pattern will continue'],
717
- confidence: pattern.confidence,
718
- nextSteps: ['Test pattern with new data', 'Formulate general rule']
719
- };
720
-
721
- session.steps.push(step);
722
- }
723
- }
724
-
725
- private async executeAbductiveReasoning(session: ReasoningSession, maxSteps: number): Promise<void> {
726
- // Inference to the best explanation
727
- const observations = this.extractObservations(session.problem);
728
- const possibleExplanations = this.generateExplanations(observations);
729
-
730
- for (let i = 0; i < maxSteps && i < possibleExplanations.length; i++) {
731
- const explanation = possibleExplanations[i];
732
-
733
- const step: ReasoningStep = {
734
- id: `step_${i}`,
735
- stepNumber: i + 1,
736
- premise: observations.join('; '),
737
- inference: `Best explanation: ${explanation.description}`,
738
- evidence: [{
739
- source: 'abductive_inference',
740
- excerpt: explanation.supportingEvidence,
741
- location: 'generated_explanation',
742
- strength: explanation.plausibility
743
- }],
744
- assumptions: explanation.assumptions,
745
- confidence: explanation.plausibility,
746
- nextSteps: possibleExplanations.slice(i + 1).map(e => `Alternative: ${e.description}`)
747
- };
748
-
749
- session.steps.push(step);
750
- }
751
- }
752
-
753
- private async executeAnalogicalReasoning(session: ReasoningSession, maxSteps: number): Promise<void> {
754
- // Reasoning by analogy
755
- const sourceDomain = this.extractDomain(session.problem);
756
- const analogies = this.findAnalogies(sourceDomain);
757
-
758
- for (let i = 0; i < maxSteps && i < analogies.length; i++) {
759
- const analogy = analogies[i];
760
-
761
- const step: ReasoningStep = {
762
- id: `step_${i}`,
763
- stepNumber: i + 1,
764
- premise: `Source domain: ${sourceDomain}`,
765
- inference: `Analogous to: ${analogy.targetDomain}. Therefore: ${analogy.inferredProperty}`,
766
- evidence: [{
767
- source: 'analogy',
768
- excerpt: `Similarity: ${analogy.similarityDescription}`,
769
- location: 'analogy_mapping',
770
- strength: analogy.similarityScore
771
- }],
772
- assumptions: ['Analogous domains share relevant properties'],
773
- confidence: analogy.similarityScore,
774
- nextSteps: analogies.slice(i + 1).map(a => `Alternative analogy: ${a.targetDomain}`)
775
- };
776
-
777
- session.steps.push(step);
778
- }
779
- }
780
-
781
- private async executeCausalReasoning(session: ReasoningSession, maxSteps: number): Promise<void> {
782
- // Cause-effect reasoning
783
- const causalChain = this.identifyCausalChain(session.problem);
784
-
785
- for (let i = 0; i < maxSteps && i < causalChain.length; i++) {
786
- const causalLink = causalChain[i];
787
-
788
- const step: ReasoningStep = {
789
- id: `step_${i}`,
790
- stepNumber: i + 1,
791
- premise: `Cause: ${causalLink.cause}`,
792
- inference: `Effect: ${causalLink.effect}`,
793
- evidence: [{
794
- source: 'causal_analysis',
795
- excerpt: causalLink.mechanism,
796
- location: 'causal_chain',
797
- strength: causalLink.confidence
798
- }],
799
- assumptions: ['Causal relationship is consistent', 'No confounding factors'],
800
- confidence: causalLink.confidence,
801
- nextSteps: causalChain.slice(i + 1).map(c => `Next effect: ${c.effect}`)
802
- };
803
-
804
- session.steps.push(step);
805
- }
806
- }
807
-
808
- private async executeCounterfactualReasoning(session: ReasoningSession, maxSteps: number): Promise<void> {
809
- // What-if reasoning
810
- const counterfactuals = this.generateCounterfactuals(session.problem);
811
-
812
- for (let i = 0; i < maxSteps && i < counterfactuals.length; i++) {
813
- const cf = counterfactuals[i];
814
-
815
- const step: ReasoningStep = {
816
- id: `step_${i}`,
817
- stepNumber: i + 1,
818
- premise: `Actual: ${cf.actual}`,
819
- inference: `If ${cf.condition}, then ${cf.outcome}`,
820
- evidence: [{
821
- source: 'counterfactual',
822
- excerpt: cf.reasoning,
823
- location: 'counterfactual_analysis',
824
- strength: cf.plausibility
825
- }],
826
- assumptions: cf.assumptions,
827
- confidence: cf.plausibility,
828
- nextSteps: counterfactuals.slice(i + 1).map(c => `Alternative: If ${c.condition}`)
829
- };
830
-
831
- session.steps.push(step);
832
- }
833
- }
834
-
835
- /**
836
- * Create and test a hypothesis
837
- */
838
- createHypothesis(statement: string): Hypothesis {
839
- return this.hypothesisManager.createHypothesis(statement);
840
- }
841
-
842
- addEvidenceToHypothesis(
843
- hypothesisId: string,
844
- evidence: Evidence,
845
- supporting: boolean
846
- ): void {
847
- this.hypothesisManager.addEvidence(hypothesisId, evidence, supporting);
848
- }
849
-
850
- /**
851
- * Decompose a complex problem
852
- */
853
- decomposeProblem(problem: string): ProblemDecomposition {
854
- return this.decompositionEngine.decompose(problem);
855
- }
856
-
857
- /**
858
- * Generate Chain of Thought for a question
859
- */
860
- generateChainOfThought(question: string, maxDepth?: number): ChainOfThought {
861
- return this.cotGenerator.generate(question, maxDepth);
862
- }
863
-
864
- // Helper methods
865
- private generateId(): string {
866
- return `reasoning_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
867
- }
868
-
869
- private extractFacts(problem: string): string[] {
870
- // Simplified fact extraction
871
- return problem
872
- .split(/[.!?]+/)
873
- .map(s => s.trim())
874
- .filter(s => s.length > 10);
875
- }
876
-
877
- private extractObservations(problem: string): string[] {
878
- return this.extractFacts(problem);
879
- }
880
-
881
- private identifyPattern(observations: string[]): { description: string; confidence: number } {
882
- // Simplified pattern identification
883
- const commonWords = this.findCommonElements(observations);
884
- return {
885
- description: `Common elements: ${commonWords.join(', ')}`,
886
- confidence: Math.min(0.9, observations.length * 0.2)
887
- };
888
- }
889
-
890
- private findCommonElements(strings: string[]): string[] {
891
- if (strings.length === 0) return [];
892
-
893
- const wordSets = strings.map(s => new Set(s.toLowerCase().split(/\s+/)));
894
- const common = Array.from(wordSets[0]).filter(word =>
895
- wordSets.every(set => set.has(word)) && word.length > 4
896
- );
897
-
898
- return common.slice(0, 5);
899
- }
900
-
901
- private generateExplanations(observations: string[]): Array<{
902
- description: string;
903
- plausibility: number;
904
- supportingEvidence: string;
905
- assumptions: string[];
906
- }> {
907
- return [
908
- {
909
- description: `Explanation based on ${observations.length} observations`,
910
- plausibility: 0.7,
911
- supportingEvidence: observations.join('; '),
912
- assumptions: ['Observations are accurate', 'No hidden factors']
913
- }
914
- ];
915
- }
916
-
917
- private extractDomain(problem: string): string {
918
- const domains = ['business', 'technology', 'science', 'health', 'education', 'finance'];
919
- const problemLower = problem.toLowerCase();
920
- return domains.find(d => problemLower.includes(d)) || 'general';
921
- }
922
-
923
- private findAnalogies(sourceDomain: string): Array<{
924
- targetDomain: string;
925
- inferredProperty: string;
926
- similarityDescription: string;
927
- similarityScore: number;
928
- }> {
929
- const analogies: Record<string, Array<{ target: string; property: string; similarity: string }>> = {
930
- business: [
931
- { target: 'ecosystem', property: 'interconnected components', similarity: 'both have interdependent parts' },
932
- { target: 'organism', property: 'growth and adaptation', similarity: 'both evolve over time' }
933
- ],
934
- technology: [
935
- { target: 'biology', property: 'modular components', similarity: 'both use building blocks' },
936
- { target: 'language', property: 'syntax and structure', similarity: 'both have rules and patterns' }
937
- ]
938
- };
939
-
940
- return (analogies[sourceDomain] || []).map(a => ({
941
- targetDomain: a.target,
942
- inferredProperty: a.property,
943
- similarityDescription: a.similarity,
944
- similarityScore: 0.7
945
- }));
946
- }
947
-
948
- private identifyCausalChain(problem: string): Array<{
949
- cause: string;
950
- effect: string;
951
- mechanism: string;
952
- confidence: number;
953
- }> {
954
- const causalIndicators = ['causes', 'leads to', 'results in', 'because', 'due to', 'therefore'];
955
- const chain: Array<{ cause: string; effect: string; mechanism: string; confidence: number }> = [];
956
-
957
- causalIndicators.forEach(indicator => {
958
- const regex = new RegExp(`(.+?)\\s+${indicator}\\s+(.+?)[.!?]`, 'gi');
959
- let match;
960
- while ((match = regex.exec(problem)) !== null) {
961
- chain.push({
962
- cause: match[1].trim(),
963
- effect: match[2].trim(),
964
- mechanism: `${match[1].trim()} ${indicator} ${match[2].trim()}`,
965
- confidence: 0.75
966
- });
967
- }
968
- });
969
-
970
- return chain.length > 0 ? chain : [{
971
- cause: 'Initial condition',
972
- effect: 'Observed outcome',
973
- mechanism: 'Causal relationship inferred from context',
974
- confidence: 0.5
975
- }];
976
- }
977
-
978
- private generateCounterfactuals(problem: string): Array<{
979
- actual: string;
980
- condition: string;
981
- outcome: string;
982
- reasoning: string;
983
- plausibility: number;
984
- assumptions: string[];
985
- }> {
986
- return [
987
- {
988
- actual: problem,
989
- condition: 'conditions were different',
990
- outcome: 'outcome would change',
991
- reasoning: 'Counterfactual analysis based on problem context',
992
- plausibility: 0.6,
993
- assumptions: ['Minimal change principle', 'Ceteris paribus']
994
- }
995
- ];
996
- }
997
-
998
- private generateConclusion(session: ReasoningSession, cot?: ChainOfThought): string {
999
- const stepConclusions = session.steps.map(s => s.inference);
1000
-
1001
- if (cot?.finalAnswer) {
1002
- return `${cot.finalAnswer} Based on ${session.steps.length} reasoning steps.`;
1003
- }
1004
-
1005
- return `After ${session.steps.length} steps of ${session.type} reasoning: ${stepConclusions.slice(-2).join('; ')}.`;
1006
- }
1007
-
1008
- private calculateSessionConfidence(session: ReasoningSession): number {
1009
- if (session.steps.length === 0) return 0;
1010
- const avgConfidence = session.steps.reduce((sum, s) => sum + s.confidence, 0) / session.steps.length;
1011
- return Math.min(0.95, avgConfidence);
1012
- }
1013
-
1014
- /**
1015
- * Get reasoning session
1016
- */
1017
- getSession(sessionId: string): ReasoningSession | undefined {
1018
- return this.sessions.get(sessionId);
1019
- }
1020
-
1021
- /**
1022
- * Add custom logical rule
1023
- */
1024
- addRule(rule: Rule): void {
1025
- this.rulesEngine.addRule(rule);
1026
- }
1027
- }
1028
-
1029
- // ============================================================================
1030
- // EXPORT SINGLETON INSTANCE
1031
- // ============================================================================
1032
-
1033
- export const reasoningEngine = new ReasoningEngine();
1034
-
1035
- // ============================================================================
1036
- // EXAMPLE USAGE
1037
- // ============================================================================
1038
-
1039
- /*
1040
- // Deductive reasoning
1041
- const deductiveResult = await reasoningEngine.reason(
1042
- "All software requires maintenance. This application is software. Therefore...",
1043
- { type: ReasoningType.DEDUCTIVE }
1044
- );
1045
-
1046
- // Inductive reasoning
1047
- const inductiveResult = await reasoningEngine.reason(
1048
- "Every software project I've seen with good documentation succeeded. " +
1049
- "Projects with poor documentation often failed. Therefore...",
1050
- { type: ReasoningType.INDUCTIVE }
1051
- );
1052
-
1053
- // Hypothesis testing
1054
- const hypothesis = reasoningEngine.createHypothesis(
1055
- "Using TypeScript reduces bug count by 30%"
1056
- );
1057
-
1058
- reasoningEngine.addEvidenceToHypothesis(
1059
- hypothesis.id,
1060
- {
1061
- source: 'study',
1062
- excerpt: 'TypeScript projects had 15% fewer bugs',
1063
- location: 'research_paper',
1064
- strength: 0.8
1065
- },
1066
- true
1067
- );
1068
-
1069
- // Problem decomposition
1070
- const decomposition = reasoningEngine.decomposeProblem(
1071
- "Build a scalable e-commerce platform with AI recommendations"
1072
- );
1073
-
1074
- // Chain of Thought
1075
- const cot = reasoningEngine.generateChainOfThought(
1076
- "How can we improve software development productivity?",
1077
- 5
1078
- );
1079
- */