@gotza02/seq-thinking 1.1.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 (106) hide show
  1. package/README.md +149 -0
  2. package/SYSTEM_INSTRUCTIONS.md +50 -0
  3. package/agents_test.log +15 -0
  4. package/dist/__tests__/agents.test.d.ts +2 -0
  5. package/dist/__tests__/agents.test.d.ts.map +1 -0
  6. package/dist/__tests__/agents.test.js +673 -0
  7. package/dist/__tests__/agents.test.js.map +1 -0
  8. package/dist/__tests__/mcp-server.test.d.ts +2 -0
  9. package/dist/__tests__/mcp-server.test.d.ts.map +1 -0
  10. package/dist/__tests__/mcp-server.test.js +315 -0
  11. package/dist/__tests__/mcp-server.test.js.map +1 -0
  12. package/dist/__tests__/sequential-thinking.test.d.ts +2 -0
  13. package/dist/__tests__/sequential-thinking.test.d.ts.map +1 -0
  14. package/dist/__tests__/sequential-thinking.test.js +545 -0
  15. package/dist/__tests__/sequential-thinking.test.js.map +1 -0
  16. package/dist/__tests__/swarm-coordinator.test.d.ts +2 -0
  17. package/dist/__tests__/swarm-coordinator.test.d.ts.map +1 -0
  18. package/dist/__tests__/swarm-coordinator.test.js +606 -0
  19. package/dist/__tests__/swarm-coordinator.test.js.map +1 -0
  20. package/dist/__tests__/types.test.d.ts +2 -0
  21. package/dist/__tests__/types.test.d.ts.map +1 -0
  22. package/dist/__tests__/types.test.js +741 -0
  23. package/dist/__tests__/types.test.js.map +1 -0
  24. package/dist/__tests__/utils.test.d.ts +2 -0
  25. package/dist/__tests__/utils.test.d.ts.map +1 -0
  26. package/dist/__tests__/utils.test.js +264 -0
  27. package/dist/__tests__/utils.test.js.map +1 -0
  28. package/dist/agents/base-agent.d.ts +126 -0
  29. package/dist/agents/base-agent.d.ts.map +1 -0
  30. package/dist/agents/base-agent.js +214 -0
  31. package/dist/agents/base-agent.js.map +1 -0
  32. package/dist/agents/critic-agent.d.ts +134 -0
  33. package/dist/agents/critic-agent.d.ts.map +1 -0
  34. package/dist/agents/critic-agent.js +484 -0
  35. package/dist/agents/critic-agent.js.map +1 -0
  36. package/dist/agents/index.d.ts +11 -0
  37. package/dist/agents/index.d.ts.map +1 -0
  38. package/dist/agents/index.js +11 -0
  39. package/dist/agents/index.js.map +1 -0
  40. package/dist/agents/meta-reasoning-agent.d.ts +143 -0
  41. package/dist/agents/meta-reasoning-agent.d.ts.map +1 -0
  42. package/dist/agents/meta-reasoning-agent.js +532 -0
  43. package/dist/agents/meta-reasoning-agent.js.map +1 -0
  44. package/dist/agents/reasoner-agent.d.ts +75 -0
  45. package/dist/agents/reasoner-agent.d.ts.map +1 -0
  46. package/dist/agents/reasoner-agent.js +226 -0
  47. package/dist/agents/reasoner-agent.js.map +1 -0
  48. package/dist/agents/synthesizer-agent.d.ts +174 -0
  49. package/dist/agents/synthesizer-agent.d.ts.map +1 -0
  50. package/dist/agents/synthesizer-agent.js +583 -0
  51. package/dist/agents/synthesizer-agent.js.map +1 -0
  52. package/dist/index.d.ts +21 -0
  53. package/dist/index.d.ts.map +1 -0
  54. package/dist/index.js +27 -0
  55. package/dist/index.js.map +1 -0
  56. package/dist/mcp-server.d.ts +823 -0
  57. package/dist/mcp-server.d.ts.map +1 -0
  58. package/dist/mcp-server.js +377 -0
  59. package/dist/mcp-server.js.map +1 -0
  60. package/dist/sequential-thinking.d.ts +91 -0
  61. package/dist/sequential-thinking.d.ts.map +1 -0
  62. package/dist/sequential-thinking.js +540 -0
  63. package/dist/sequential-thinking.js.map +1 -0
  64. package/dist/swarm-coordinator.d.ts +188 -0
  65. package/dist/swarm-coordinator.d.ts.map +1 -0
  66. package/dist/swarm-coordinator.js +627 -0
  67. package/dist/swarm-coordinator.js.map +1 -0
  68. package/dist/types/index.d.ts +806 -0
  69. package/dist/types/index.d.ts.map +1 -0
  70. package/dist/types/index.js +279 -0
  71. package/dist/types/index.js.map +1 -0
  72. package/dist/utils/index.d.ts +421 -0
  73. package/dist/utils/index.d.ts.map +1 -0
  74. package/dist/utils/index.js +864 -0
  75. package/dist/utils/index.js.map +1 -0
  76. package/dist/utils/llm-adapter.d.ts +23 -0
  77. package/dist/utils/llm-adapter.d.ts.map +1 -0
  78. package/dist/utils/llm-adapter.js +68 -0
  79. package/dist/utils/llm-adapter.js.map +1 -0
  80. package/dist/utils/persistence.d.ts +33 -0
  81. package/dist/utils/persistence.d.ts.map +1 -0
  82. package/dist/utils/persistence.js +108 -0
  83. package/dist/utils/persistence.js.map +1 -0
  84. package/package.json +41 -0
  85. package/src/__tests__/agents.test.ts +858 -0
  86. package/src/__tests__/mcp-server.test.ts +380 -0
  87. package/src/__tests__/sequential-thinking.test.ts +687 -0
  88. package/src/__tests__/swarm-coordinator.test.ts +903 -0
  89. package/src/__tests__/types.test.ts +839 -0
  90. package/src/__tests__/utils.test.ts +322 -0
  91. package/src/agents/base-agent.ts +285 -0
  92. package/src/agents/critic-agent.ts +582 -0
  93. package/src/agents/index.ts +11 -0
  94. package/src/agents/meta-reasoning-agent.ts +672 -0
  95. package/src/agents/reasoner-agent.ts +312 -0
  96. package/src/agents/synthesizer-agent.ts +758 -0
  97. package/src/index.ts +118 -0
  98. package/src/mcp-server.ts +387 -0
  99. package/src/sequential-thinking.ts +560 -0
  100. package/src/swarm-coordinator.ts +744 -0
  101. package/src/types/index.ts +915 -0
  102. package/src/utils/index.ts +1004 -0
  103. package/src/utils/llm-adapter.ts +76 -0
  104. package/src/utils/persistence.ts +108 -0
  105. package/test_output.log +0 -0
  106. package/tsconfig.json +21 -0
@@ -0,0 +1,672 @@
1
+ /**
2
+ * Meta-Reasoning Agent Implementation
3
+ * @module agents/meta-reasoning-agent
4
+ * @version 1.0.0
5
+ */
6
+
7
+ import { BaseAgent } from './base-agent.js';
8
+ import {
9
+ AgentType,
10
+ ThoughtType,
11
+ type Task,
12
+ type TaskResult,
13
+ type AgentCapability,
14
+ type Thought,
15
+ type ThinkingSession
16
+ } from '../types/index.js';
17
+
18
+ /**
19
+ * Meta-observation
20
+ */
21
+ interface MetaObservation {
22
+ type: 'pattern' | 'concern' | 'insight' | 'suggestion';
23
+ description: string;
24
+ severity?: 'low' | 'medium' | 'high';
25
+ recommendation?: string;
26
+ triggeredActions?: string[];
27
+ }
28
+
29
+ /**
30
+ * Thinking pattern
31
+ */
32
+ interface ThinkingPattern {
33
+ pattern: string;
34
+ frequency: number;
35
+ impact: 'positive' | 'negative' | 'neutral';
36
+ suggestion?: string;
37
+ }
38
+
39
+ /**
40
+ * Meta-reasoning agent that reflects on thinking processes
41
+ */
42
+ export class MetaReasoningAgent extends BaseAgent {
43
+ /** Observation history */
44
+ private observationHistory: MetaObservation[] = [];
45
+
46
+ /**
47
+ * Create a new meta-reasoning agent
48
+ * @param config - Agent configuration
49
+ */
50
+ constructor(config: {
51
+ name: string;
52
+ capabilities?: AgentCapability[];
53
+ }) {
54
+ const defaultCapabilities: AgentCapability[] = [
55
+ {
56
+ name: 'process_reflection',
57
+ description: 'Reflect on thinking processes',
58
+ confidence: 0.9,
59
+ performanceMetrics: { tasksCompleted: 0, averageQuality: 0, averageTimeMs: 0 }
60
+ },
61
+ {
62
+ name: 'strategy_assessment',
63
+ description: 'Assess reasoning strategies',
64
+ confidence: 0.85,
65
+ performanceMetrics: { tasksCompleted: 0, averageQuality: 0, averageTimeMs: 0 }
66
+ },
67
+ {
68
+ name: 'bias_detection',
69
+ description: 'Detect cognitive biases',
70
+ confidence: 0.8,
71
+ performanceMetrics: { tasksCompleted: 0, averageQuality: 0, averageTimeMs: 0 }
72
+ },
73
+ {
74
+ name: 'pattern_analysis',
75
+ description: 'Analyze thinking patterns',
76
+ confidence: 0.85,
77
+ performanceMetrics: { tasksCompleted: 0, averageQuality: 0, averageTimeMs: 0 }
78
+ }
79
+ ];
80
+
81
+ super({
82
+ name: config.name,
83
+ type: AgentType.META_REASONING,
84
+ capabilities: config.capabilities || defaultCapabilities,
85
+ maxConcurrentTasks: 5,
86
+ confidenceThreshold: 0.7
87
+ });
88
+ }
89
+
90
+ /**
91
+ * Get agent type
92
+ * @returns Agent type
93
+ */
94
+ getType(): string {
95
+ return AgentType.META_REASONING;
96
+ }
97
+
98
+ /**
99
+ * Get agent capabilities
100
+ * @returns Array of capabilities
101
+ */
102
+ getCapabilities(): AgentCapability[] {
103
+ return this.config.capabilities;
104
+ }
105
+
106
+ /**
107
+ * Process a task - perform meta-reasoning
108
+ * @param task - Task to process
109
+ * @returns Task result
110
+ */
111
+ async process(task: Task): Promise<TaskResult> {
112
+ const startTime = Date.now();
113
+ const input = task.input as {
114
+ session?: ThinkingSession;
115
+ thoughts?: Thought[];
116
+ operation: 'reflect' | 'analyze_patterns' | 'assess_strategy' | 'detect_bias';
117
+ };
118
+
119
+ let result: unknown;
120
+ let confidence = 0.8;
121
+
122
+ switch (input.operation) {
123
+ case 'reflect':
124
+ result = this.reflect(input.session);
125
+ break;
126
+ case 'analyze_patterns':
127
+ result = this.analyzeThinkingPatterns(input.thoughts || []);
128
+ break;
129
+ case 'assess_strategy':
130
+ result = this.assessStrategy(input.session);
131
+ break;
132
+ case 'detect_bias':
133
+ result = this.detectBias(input.thoughts || []);
134
+ break;
135
+ default:
136
+ result = this.reflect(input.session);
137
+ }
138
+
139
+ return this.createTaskResult(
140
+ task.id,
141
+ result,
142
+ confidence,
143
+ Date.now() - startTime,
144
+ {
145
+ reasoningSteps: 1,
146
+ intermediateResults: []
147
+ }
148
+ );
149
+ }
150
+
151
+ /**
152
+ * Reflect on a thinking session
153
+ * @param session - Session to reflect on
154
+ * @returns Reflection result
155
+ */
156
+ reflect(session?: ThinkingSession): {
157
+ reflection: string;
158
+ insights: string[];
159
+ recommendations: string[];
160
+ observations: MetaObservation[];
161
+ } {
162
+ if (!session) {
163
+ return {
164
+ reflection: 'No session provided for reflection',
165
+ insights: [],
166
+ recommendations: [],
167
+ observations: []
168
+ };
169
+ }
170
+
171
+ const thoughts = Array.from(session.thoughts.values());
172
+ const insights: string[] = [];
173
+ const recommendations: string[] = [];
174
+ const observations: MetaObservation[] = [];
175
+
176
+ // Analyze thinking patterns
177
+ const patterns = this.analyzeThinkingPatterns(thoughts);
178
+
179
+ for (const pattern of patterns) {
180
+ if (pattern.impact === 'negative') {
181
+ observations.push({
182
+ type: 'concern',
183
+ description: pattern.pattern,
184
+ severity: pattern.frequency > 3 ? 'high' : 'medium',
185
+ recommendation: pattern.suggestion
186
+ });
187
+ recommendations.push(pattern.suggestion || 'Review and adjust thinking pattern');
188
+ } else if (pattern.impact === 'positive') {
189
+ observations.push({
190
+ type: 'insight',
191
+ description: pattern.pattern
192
+ });
193
+ insights.push(pattern.pattern);
194
+ }
195
+ }
196
+
197
+ // Check confidence trends
198
+ const confidenceTrend = this.analyzeConfidenceTrend(thoughts);
199
+ if (confidenceTrend.trend === 'declining') {
200
+ observations.push({
201
+ type: 'concern',
202
+ description: 'Confidence is declining over time',
203
+ severity: 'medium',
204
+ recommendation: 'Review assumptions and gather more evidence'
205
+ });
206
+ recommendations.push('Strengthen reasoning with additional evidence');
207
+ } else if (confidenceTrend.trend === 'improving') {
208
+ insights.push('Confidence is improving, indicating solid reasoning progress');
209
+ }
210
+
211
+ // Check thought type distribution
212
+ const typeDistribution = this.analyzeThoughtTypeDistribution(thoughts);
213
+ const analysisCount = typeDistribution.get(ThoughtType.ANALYSIS) || 0;
214
+ const hypothesisCount = typeDistribution.get(ThoughtType.HYPOTHESIS) || 0;
215
+
216
+ if (analysisCount > hypothesisCount * 3) {
217
+ observations.push({
218
+ type: 'suggestion',
219
+ description: 'Heavy focus on analysis with limited hypothesis generation',
220
+ recommendation: 'Consider exploring more alternative hypotheses'
221
+ });
222
+ recommendations.push('Generate more diverse hypotheses');
223
+ }
224
+
225
+ // Check for meta-reasoning gaps
226
+ const metaThoughtCount = thoughts.filter(t => t.thoughtType === ThoughtType.META_REASONING).length;
227
+ if (metaThoughtCount < thoughts.length * 0.1) {
228
+ observations.push({
229
+ type: 'suggestion',
230
+ description: 'Limited meta-reasoning detected',
231
+ recommendation: 'Increase reflection on the thinking process itself'
232
+ });
233
+ recommendations.push('Add more meta-reasoning steps');
234
+ }
235
+
236
+ const reflection = `Analyzed ${thoughts.length} thoughts across ${session.branches.size} branches. ` +
237
+ `Found ${insights.length} positive insights and ${recommendations.length} areas for improvement.`;
238
+
239
+ return {
240
+ reflection,
241
+ insights,
242
+ recommendations,
243
+ observations
244
+ };
245
+ }
246
+
247
+ /**
248
+ * Analyze thinking patterns
249
+ * @param thoughts - Thoughts to analyze
250
+ * @returns Array of patterns
251
+ */
252
+ analyzeThinkingPatterns(thoughts: Thought[]): ThinkingPattern[] {
253
+ const patterns: ThinkingPattern[] = [];
254
+
255
+ if (thoughts.length === 0) return patterns;
256
+
257
+ // Pattern: Repetitive thinking
258
+ const contentSimilarities = this.findSimilarThoughts(thoughts);
259
+ if (contentSimilarities.length > thoughts.length * 0.3) {
260
+ patterns.push({
261
+ pattern: 'Repetitive thinking detected - similar thoughts being generated',
262
+ frequency: contentSimilarities.length,
263
+ impact: 'negative',
264
+ suggestion: 'Focus on generating novel insights rather than restating'
265
+ });
266
+ }
267
+
268
+ // Pattern: Confidence progression
269
+ const confidenceValues = thoughts.map(t => t.confidence.overall);
270
+ const avgConfidence = confidenceValues.reduce((a, b) => a + b, 0) / confidenceValues.length;
271
+
272
+ if (avgConfidence < 0.5) {
273
+ patterns.push({
274
+ pattern: 'Low average confidence across thoughts',
275
+ frequency: thoughts.length,
276
+ impact: 'negative',
277
+ suggestion: 'Strengthen evidence and reasoning for key claims'
278
+ });
279
+ } else if (avgConfidence > 0.8) {
280
+ patterns.push({
281
+ pattern: 'High confidence maintained throughout',
282
+ frequency: thoughts.length,
283
+ impact: 'positive'
284
+ });
285
+ }
286
+
287
+ // Pattern: Branch exploration
288
+ const branchIds = new Set(thoughts.map(t => t.branchId));
289
+ if (branchIds.size === 1 && thoughts.length > 5) {
290
+ patterns.push({
291
+ pattern: 'Single branch exploration - no parallel hypotheses',
292
+ frequency: 1,
293
+ impact: 'negative',
294
+ suggestion: 'Consider branching to explore alternative approaches'
295
+ });
296
+ } else if (branchIds.size > 2) {
297
+ patterns.push({
298
+ pattern: 'Active branch exploration with parallel hypotheses',
299
+ frequency: branchIds.size,
300
+ impact: 'positive'
301
+ });
302
+ }
303
+
304
+ // Pattern: Assumption documentation
305
+ const thoughtsWithAssumptions = thoughts.filter(t => t.assumptions.length > 0).length;
306
+ if (thoughtsWithAssumptions < thoughts.length * 0.3) {
307
+ patterns.push({
308
+ pattern: 'Limited explicit assumption documentation',
309
+ frequency: thoughts.length - thoughtsWithAssumptions,
310
+ impact: 'negative',
311
+ suggestion: 'Document assumptions explicitly for each major claim'
312
+ });
313
+ }
314
+
315
+ // Pattern: Revision activity
316
+ const revisedThoughts = thoughts.filter(t => t.revisionHistory.length > 0).length;
317
+ if (revisedThoughts > thoughts.length * 0.5) {
318
+ patterns.push({
319
+ pattern: 'High revision rate - thoughts being frequently corrected',
320
+ frequency: revisedThoughts,
321
+ impact: 'neutral',
322
+ suggestion: 'Consider more careful initial analysis to reduce revisions'
323
+ });
324
+ }
325
+
326
+ return patterns;
327
+ }
328
+
329
+ /**
330
+ * Assess reasoning strategy
331
+ * @param session - Session to assess
332
+ * @returns Strategy assessment
333
+ */
334
+ assessStrategy(session?: ThinkingSession): {
335
+ assessment: string;
336
+ strengths: string[];
337
+ weaknesses: string[];
338
+ suggestions: string[];
339
+ } {
340
+ if (!session) {
341
+ return {
342
+ assessment: 'No session provided',
343
+ strengths: [],
344
+ weaknesses: [],
345
+ suggestions: []
346
+ };
347
+ }
348
+
349
+ const thoughts = Array.from(session.thoughts.values());
350
+ const strengths: string[] = [];
351
+ const weaknesses: string[] = [];
352
+ const suggestions: string[] = [];
353
+
354
+ // Assess hypothesis generation
355
+ const hypothesisCount = thoughts.filter(t => t.thoughtType === ThoughtType.HYPOTHESIS).length;
356
+ if (hypothesisCount >= 3) {
357
+ strengths.push('Good hypothesis generation with multiple alternatives');
358
+ } else if (hypothesisCount < 2 && thoughts.length > 5) {
359
+ weaknesses.push('Limited hypothesis generation');
360
+ suggestions.push('Generate at least 3 alternative hypotheses early in the process');
361
+ }
362
+
363
+ // Assess evidence gathering
364
+ const evidenceCount = thoughts.filter(t => t.thoughtType === ThoughtType.EVIDENCE).length;
365
+ if (evidenceCount >= thoughts.length * 0.2) {
366
+ strengths.push('Strong evidence-based reasoning');
367
+ } else {
368
+ weaknesses.push('Insufficient evidence gathering');
369
+ suggestions.push('Support claims with more evidence and citations');
370
+ }
371
+
372
+ // Assess counterargument consideration
373
+ const counterCount = thoughts.filter(t => t.thoughtType === ThoughtType.COUNTERARGUMENT).length;
374
+ if (counterCount >= 2) {
375
+ strengths.push('Good consideration of counterarguments');
376
+ } else if (thoughts.length > 8) {
377
+ weaknesses.push('Limited counterargument analysis');
378
+ suggestions.push('Actively seek and address counterarguments');
379
+ }
380
+
381
+ // Assess synthesis
382
+ const synthesisCount = thoughts.filter(t => t.thoughtType === ThoughtType.SYNTHESIS).length;
383
+ if (synthesisCount >= 2) {
384
+ strengths.push('Regular synthesis of findings');
385
+ } else if (thoughts.length > 10) {
386
+ suggestions.push('Periodically synthesize findings to maintain coherence');
387
+ }
388
+
389
+ // Assess self-correction
390
+ const correctionCount = thoughts.filter(t => t.thoughtType === ThoughtType.SELF_CORRECTION).length;
391
+ if (correctionCount >= 1) {
392
+ strengths.push('Active self-correction detected');
393
+ }
394
+
395
+ const assessment = strengths.length > weaknesses.length
396
+ ? 'Overall effective reasoning strategy'
397
+ : weaknesses.length > strengths.length
398
+ ? 'Strategy needs improvement'
399
+ : 'Balanced strategy with room for improvement';
400
+
401
+ return {
402
+ assessment,
403
+ strengths,
404
+ weaknesses,
405
+ suggestions
406
+ };
407
+ }
408
+
409
+ /**
410
+ * Detect cognitive biases
411
+ * @param thoughts - Thoughts to analyze
412
+ * @returns Bias detection results
413
+ */
414
+ detectBias(thoughts: Thought[]): {
415
+ detectedBiases: Array<{
416
+ bias: string;
417
+ evidence: string;
418
+ severity: 'low' | 'medium' | 'high';
419
+ mitigation: string;
420
+ }>;
421
+ overallRisk: 'low' | 'medium' | 'high';
422
+ } {
423
+ const detectedBiases: Array<{
424
+ bias: string;
425
+ evidence: string;
426
+ severity: 'low' | 'medium' | 'high';
427
+ mitigation: string;
428
+ }> = [];
429
+
430
+ if (thoughts.length === 0) {
431
+ return { detectedBiases, overallRisk: 'low' };
432
+ }
433
+
434
+ // Check for confirmation bias
435
+ const confirmingThoughts = thoughts.filter(t =>
436
+ t.content.toLowerCase().includes('confirms') ||
437
+ t.content.toLowerCase().includes('proves') ||
438
+ t.content.toLowerCase().includes('supports')
439
+ ).length;
440
+
441
+ const disconfirmingThoughts = thoughts.filter(t =>
442
+ t.content.toLowerCase().includes('contradicts') ||
443
+ t.content.toLowerCase().includes('challenges') ||
444
+ t.content.toLowerCase().includes('refutes')
445
+ ).length;
446
+
447
+ if (confirmingThoughts > disconfirmingThoughts * 3 && confirmingThoughts > 2) {
448
+ detectedBiases.push({
449
+ bias: 'Confirmation Bias',
450
+ evidence: `${confirmingThoughts} confirming vs ${disconfirmingThoughts} disconfirming thoughts`,
451
+ severity: 'medium',
452
+ mitigation: 'Actively seek disconfirming evidence for each claim'
453
+ });
454
+ }
455
+
456
+ // Check for anchoring bias
457
+ const firstThoughtConfidence = thoughts[0]?.confidence.overall || 0.5;
458
+ const confidenceVariance = this.calculateConfidenceVariance(thoughts);
459
+
460
+ if (confidenceVariance < 0.1 && thoughts.length > 5) {
461
+ detectedBiases.push({
462
+ bias: 'Anchoring Bias',
463
+ evidence: 'Low confidence variance suggests anchoring to initial estimates',
464
+ severity: 'low',
465
+ mitigation: 'Re-evaluate confidence independently for each thought'
466
+ });
467
+ }
468
+
469
+ // Check for availability bias
470
+ const recentThoughts = thoughts.slice(-3);
471
+ const recentReferences = recentThoughts.filter(t =>
472
+ t.dependencies.some(d => thoughts.slice(0, -3).some(pt => pt.id === d))
473
+ ).length;
474
+
475
+ if (recentReferences === 0 && thoughts.length > 5) {
476
+ detectedBiases.push({
477
+ bias: 'Availability Bias',
478
+ evidence: 'Recent thoughts do not reference earlier work',
479
+ severity: 'low',
480
+ mitigation: 'Actively reference and build upon earlier insights'
481
+ });
482
+ }
483
+
484
+ // Check for overconfidence
485
+ const highConfidenceCount = thoughts.filter(t => t.confidence.overall > 0.9).length;
486
+ if (highConfidenceCount > thoughts.length * 0.5) {
487
+ detectedBiases.push({
488
+ bias: 'Overconfidence Bias',
489
+ evidence: `${highConfidenceCount}/${thoughts.length} thoughts have >90% confidence`,
490
+ severity: 'medium',
491
+ mitigation: 'Calibrate confidence more conservatively'
492
+ });
493
+ }
494
+
495
+ // Check for sunk cost fallacy
496
+ const revisionCount = thoughts.filter(t => t.revisionHistory.length > 0).length;
497
+ if (revisionCount > thoughts.length * 0.7 && thoughts.length > 5) {
498
+ detectedBiases.push({
499
+ bias: 'Sunk Cost Fallacy',
500
+ evidence: 'High revision rate may indicate reluctance to abandon initial approach',
501
+ severity: 'low',
502
+ mitigation: 'Be willing to start fresh if current approach is not working'
503
+ });
504
+ }
505
+
506
+ // Determine overall risk
507
+ const highSeverityCount = detectedBiases.filter(b => b.severity === 'high').length;
508
+ const mediumSeverityCount = detectedBiases.filter(b => b.severity === 'medium').length;
509
+
510
+ let overallRisk: 'low' | 'medium' | 'high' = 'low';
511
+ if (highSeverityCount > 0 || mediumSeverityCount > 2) {
512
+ overallRisk = 'high';
513
+ } else if (mediumSeverityCount > 0) {
514
+ overallRisk = 'medium';
515
+ }
516
+
517
+ return { detectedBiases, overallRisk };
518
+ }
519
+
520
+ // ============================================================================
521
+ // Helper Methods
522
+ // ============================================================================
523
+
524
+ /**
525
+ * Find similar thoughts
526
+ * @param thoughts - Thoughts to compare
527
+ * @returns Array of similar thought pairs
528
+ */
529
+ private findSimilarThoughts(thoughts: Thought[]): Array<[Thought, Thought]> {
530
+ const similar: Array<[Thought, Thought]> = [];
531
+
532
+ for (let i = 0; i < thoughts.length; i++) {
533
+ for (let j = i + 1; j < thoughts.length; j++) {
534
+ if (this.thoughtsAreSimilar(thoughts[i], thoughts[j])) {
535
+ similar.push([thoughts[i], thoughts[j]]);
536
+ }
537
+ }
538
+ }
539
+
540
+ return similar;
541
+ }
542
+
543
+ /**
544
+ * Check if two thoughts are similar
545
+ * @param a - First thought
546
+ * @param b - Second thought
547
+ * @returns True if similar
548
+ */
549
+ private thoughtsAreSimilar(a: Thought, b: Thought): boolean {
550
+ const wordsA = new Set(a.content.toLowerCase().split(/\s+/));
551
+ const wordsB = new Set(b.content.toLowerCase().split(/\s+/));
552
+ const intersection = [...wordsA].filter(w => wordsB.has(w));
553
+ const union = new Set([...wordsA, ...wordsB]);
554
+
555
+ return union.size > 0 && intersection.length / union.size > 0.7;
556
+ }
557
+
558
+ /**
559
+ * Analyze confidence trend
560
+ * @param thoughts - Thoughts to analyze
561
+ * @returns Trend analysis
562
+ */
563
+ private analyzeConfidenceTrend(thoughts: Thought[]): {
564
+ trend: 'improving' | 'declining' | 'stable';
565
+ initial: number;
566
+ final: number;
567
+ } {
568
+ if (thoughts.length < 3) {
569
+ return { trend: 'stable', initial: 0, final: 0 };
570
+ }
571
+
572
+ const sorted = [...thoughts].sort((a, b) =>
573
+ a.metadata.createdAt.getTime() - b.metadata.createdAt.getTime()
574
+ );
575
+
576
+ const firstThird = sorted.slice(0, Math.ceil(sorted.length / 3));
577
+ const lastThird = sorted.slice(-Math.ceil(sorted.length / 3));
578
+
579
+ const initial = firstThird.reduce((sum, t) => sum + t.confidence.overall, 0) / firstThird.length;
580
+ const final = lastThird.reduce((sum, t) => sum + t.confidence.overall, 0) / lastThird.length;
581
+
582
+ const diff = final - initial;
583
+ const threshold = 0.1;
584
+
585
+ let trend: 'improving' | 'declining' | 'stable';
586
+ if (diff > threshold) {
587
+ trend = 'improving';
588
+ } else if (diff < -threshold) {
589
+ trend = 'declining';
590
+ } else {
591
+ trend = 'stable';
592
+ }
593
+
594
+ return { trend, initial, final };
595
+ }
596
+
597
+ /**
598
+ * Analyze thought type distribution
599
+ * @param thoughts - Thoughts to analyze
600
+ * @returns Type distribution map
601
+ */
602
+ private analyzeThoughtTypeDistribution(thoughts: Thought[]): Map<ThoughtType, number> {
603
+ const distribution = new Map<ThoughtType, number>();
604
+
605
+ for (const thought of thoughts) {
606
+ const count = distribution.get(thought.thoughtType) || 0;
607
+ distribution.set(thought.thoughtType, count + 1);
608
+ }
609
+
610
+ return distribution;
611
+ }
612
+
613
+ /**
614
+ * Calculate confidence variance
615
+ * @param thoughts - Thoughts to analyze
616
+ * @returns Variance
617
+ */
618
+ private calculateConfidenceVariance(thoughts: Thought[]): number {
619
+ if (thoughts.length < 2) return 0;
620
+
621
+ const values = thoughts.map(t => t.confidence.overall);
622
+ const mean = values.reduce((a, b) => a + b, 0) / values.length;
623
+ const squaredDiffs = values.map(v => Math.pow(v - mean, 2));
624
+
625
+ return squaredDiffs.reduce((a, b) => a + b, 0) / values.length;
626
+ }
627
+
628
+ /**
629
+ * Generate meta-observation for a thought
630
+ * @param thought - Thought to analyze
631
+ * @returns Meta-observation or null
632
+ */
633
+ generateMetaObservation(thought: Thought): MetaObservation | null {
634
+ const observations: string[] = [];
635
+ const triggeredActions: string[] = [];
636
+
637
+ // Check for high uncertainty
638
+ const uncertaintyRange = thought.confidence.uncertaintyBounds[1] - thought.confidence.uncertaintyBounds[0];
639
+ if (uncertaintyRange > 0.4) {
640
+ observations.push('High uncertainty detected');
641
+ triggeredActions.push('gather_more_evidence');
642
+ }
643
+
644
+ // Check for low confidence
645
+ if (thought.confidence.overall < 0.4) {
646
+ observations.push('Low confidence in this thought');
647
+ triggeredActions.push('review_reasoning');
648
+ }
649
+
650
+ // Check for missing assumptions
651
+ if (thought.assumptions.length === 0) {
652
+ observations.push('No explicit assumptions documented');
653
+ triggeredActions.push('document_assumptions');
654
+ }
655
+
656
+ if (observations.length === 0) return null;
657
+
658
+ return {
659
+ type: 'pattern',
660
+ description: observations.join('; '),
661
+ triggeredActions
662
+ };
663
+ }
664
+
665
+ /**
666
+ * Get observation history
667
+ * @returns Observation history
668
+ */
669
+ getObservationHistory(): MetaObservation[] {
670
+ return [...this.observationHistory];
671
+ }
672
+ }