@gotza02/mathinking 3.1.6 → 3.1.8

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 (40) hide show
  1. package/README.md +7 -1
  2. package/dist/schemas/brain.schema.d.ts +16 -0
  3. package/dist/schemas/brain.schema.d.ts.map +1 -1
  4. package/dist/schemas/brain.schema.js +14 -10
  5. package/dist/schemas/brain.schema.js.map +1 -1
  6. package/dist/test-new-features.d.ts +2 -0
  7. package/dist/test-new-features.d.ts.map +1 -0
  8. package/dist/test-new-features.js +62 -0
  9. package/dist/test-new-features.js.map +1 -0
  10. package/dist/tools/orchestrator.d.ts.map +1 -1
  11. package/dist/tools/orchestrator.js +93 -26
  12. package/dist/tools/orchestrator.js.map +1 -1
  13. package/dist/tools/sequential-thinking.d.ts +2 -0
  14. package/dist/tools/sequential-thinking.d.ts.map +1 -1
  15. package/dist/tools/sequential-thinking.js +253 -42
  16. package/dist/tools/sequential-thinking.js.map +1 -1
  17. package/dist/types/index.d.ts +17 -2
  18. package/dist/types/index.d.ts.map +1 -1
  19. package/dist/utils/dag.d.ts.map +1 -1
  20. package/dist/utils/dag.js +4 -7
  21. package/dist/utils/dag.js.map +1 -1
  22. package/dist/utils/memory.d.ts +2 -2
  23. package/dist/utils/memory.d.ts.map +1 -1
  24. package/dist/utils/memory.js +9 -5
  25. package/dist/utils/memory.js.map +1 -1
  26. package/dist/utils/mutex.d.ts.map +1 -1
  27. package/dist/utils/mutex.js +1 -1
  28. package/dist/utils/mutex.js.map +1 -1
  29. package/dist/utils/resilience.d.ts.map +1 -1
  30. package/dist/utils/resilience.js +5 -8
  31. package/dist/utils/resilience.js.map +1 -1
  32. package/dist/utils/tool-cache.d.ts +2 -2
  33. package/dist/utils/tool-cache.d.ts.map +1 -1
  34. package/dist/utils/tool-cache.js +2 -0
  35. package/dist/utils/tool-cache.js.map +1 -1
  36. package/dist/utils/vector-memory.d.ts +1 -1
  37. package/dist/utils/vector-memory.d.ts.map +1 -1
  38. package/dist/utils/vector-memory.js +5 -5
  39. package/dist/utils/vector-memory.js.map +1 -1
  40. package/package.json +1 -1
@@ -67,7 +67,8 @@ export class SequentialThinkingManager {
67
67
  // Force cleanup by calling purge (if available) or by checking entries
68
68
  for (const [key, value] of this.sessions.entries()) {
69
69
  const age = Date.now() - new Date(value.updatedAt).getTime();
70
- if (age > 1000 * 60 * 60 * 24) { // 24 hours
70
+ if (age > 1000 * 60 * 60 * 24) {
71
+ // 24 hours
71
72
  this.sessions.delete(key);
72
73
  }
73
74
  }
@@ -107,14 +108,14 @@ export class SequentialThinkingManager {
107
108
  try {
108
109
  data = await fs.readFile(this.storagePath, 'utf8');
109
110
  }
110
- catch (primaryError) {
111
+ catch {
111
112
  // Primary storage failed, try backup
112
113
  try {
113
114
  console.log('[Brain] Primary storage not found, trying backup...');
114
115
  data = await fs.readFile(this.backupPath, 'utf8');
115
116
  useBackup = true;
116
117
  }
117
- catch (backupError) {
118
+ catch {
118
119
  // Backup also failed, start fresh
119
120
  console.log('[Brain] No existing storage found, starting fresh');
120
121
  this.initialized = true;
@@ -234,10 +235,10 @@ export class SequentialThinkingManager {
234
235
  innerResult = this.startSession(validatedInput);
235
236
  break;
236
237
  case 'add_thought':
237
- innerResult = this.addThought(validatedInput);
238
+ innerResult = await this.addThought(validatedInput);
238
239
  break;
239
240
  case 'create_branch':
240
- innerResult = this.createBranch(validatedInput);
241
+ innerResult = await this.createBranch(validatedInput);
241
242
  break;
242
243
  case 'generate_options':
243
244
  innerResult = this.generateOptions(validatedInput);
@@ -249,16 +250,16 @@ export class SequentialThinkingManager {
249
250
  innerResult = this.selectOption(validatedInput);
250
251
  break;
251
252
  case 'revise_thought':
252
- innerResult = this.reviseThought(validatedInput);
253
+ innerResult = await this.reviseThought(validatedInput);
253
254
  break;
254
255
  case 'set_hypothesis':
255
- innerResult = this.setHypothesis(validatedInput);
256
+ innerResult = await this.setHypothesis(validatedInput);
256
257
  break;
257
258
  case 'verify_hypothesis':
258
- innerResult = this.verifyHypothesis(validatedInput);
259
+ innerResult = await this.verifyHypothesis(validatedInput);
259
260
  break;
260
261
  case 'conclude':
261
- innerResult = this.conclude(validatedInput);
262
+ innerResult = await this.conclude(validatedInput);
262
263
  break;
263
264
  // execute_conclusion handled outside
264
265
  case 'reflect':
@@ -276,7 +277,8 @@ export class SequentialThinkingManager {
276
277
  case 'get_history':
277
278
  innerResult = this.getHistory(validatedInput);
278
279
  break;
279
- default: innerResult = this.startSession(validatedInput);
280
+ default:
281
+ innerResult = this.startSession(validatedInput);
280
282
  }
281
283
  if (innerResult.success)
282
284
  await this._saveToStorage();
@@ -317,6 +319,7 @@ export class SequentialThinkingManager {
317
319
  }
318
320
  research(input) {
319
321
  const session = this.getSession(input.sessionId);
322
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
320
323
  if (!session)
321
324
  return { success: false, message: 'Session not found' };
322
325
  const topic = input.thought || session.problemStatement;
@@ -391,13 +394,15 @@ export class SequentialThinkingManager {
391
394
  suggestedPlan = {
392
395
  planId: 'recovery-' + uuidv4().substring(0, 8),
393
396
  name: 'Network Recovery Plan',
394
- tasks: [{
397
+ tasks: [
398
+ {
395
399
  id: 'fallback',
396
400
  name: 'Fallback Echo',
397
401
  toolName: 'echo',
398
402
  toolInput: { msg: 'Recovered using fallback echo due to network failure.' },
399
403
  dependencies: []
400
- }]
404
+ }
405
+ ]
401
406
  };
402
407
  }
403
408
  return {
@@ -420,6 +425,8 @@ export class SequentialThinkingManager {
420
425
  thoughtHistory: [],
421
426
  branches: [],
422
427
  status: 'in_progress',
428
+ thinkingStyle: input.thinkingStyle || 'Analytical',
429
+ currentPhase: input.phase || 'Definition',
423
430
  createdAt: new Date().toISOString(),
424
431
  updatedAt: new Date().toISOString()
425
432
  };
@@ -427,10 +434,12 @@ export class SequentialThinkingManager {
427
434
  this.lastSessionId = sessionId;
428
435
  // 🔧 NEW: Query past solutions for context
429
436
  this.queryPastSolutions(session.problemStatement)
430
- .then(solutions => {
437
+ .then((solutions) => {
431
438
  if (solutions.length > 0) {
432
439
  console.log(`[Brain] Found ${solutions.length} similar past problems`);
433
- const context = solutions.map(s => `- ${s.problem} (relevance: ${(s.relevance * 100).toFixed(0)}%)\n Patterns: ${s.patterns.join(', ')}`).join('\n');
440
+ const context = solutions
441
+ .map((s) => `- ${s.problem} (relevance: ${(s.relevance * 100).toFixed(0)}%)\n Patterns: ${s.patterns.join(', ')}`)
442
+ .join('\n');
434
443
  // Add as a thought for AI to see
435
444
  const thought = {
436
445
  id: uuidv4(),
@@ -446,20 +455,25 @@ export class SequentialThinkingManager {
446
455
  this._saveToStorage();
447
456
  }
448
457
  })
449
- .catch(err => console.warn('[Brain] Failed to query past solutions:', err));
458
+ .catch((err) => console.warn('[Brain] Failed to query past solutions:', err));
450
459
  return {
451
460
  success: true,
452
461
  sessionId,
453
462
  currentStep: 0,
454
463
  totalThoughts: session.totalThoughts,
455
464
  status: 'in_progress',
456
- message: 'Brain 2.0 Session Started. Ready for Tree of Thoughts. Querying past solutions...'
465
+ message: `Brain 2.0 Session Started. Style: ${session.thinkingStyle}, Phase: ${session.currentPhase}. Ready for Tree of Thoughts. Querying past solutions...`
457
466
  };
458
467
  }
459
- addThought(input) {
468
+ async addThought(input) {
460
469
  const session = this.getSession(input.sessionId);
470
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
461
471
  if (!session)
462
472
  return { success: false, message: 'Session not found' };
473
+ if (input.phase)
474
+ session.currentPhase = input.phase;
475
+ if (input.thinkingStyle)
476
+ session.thinkingStyle = input.thinkingStyle;
463
477
  session.currentStep++;
464
478
  const thought = {
465
479
  id: uuidv4(),
@@ -469,9 +483,56 @@ export class SequentialThinkingManager {
469
483
  timestamp: new Date().toISOString(),
470
484
  confidence: input.confidence ?? 70, // Default confidence
471
485
  parentId: input.branchFromThoughtId || this.getLastThoughtId(session),
472
- branchLabel: input.branchLabel // Preserve label
486
+ branchLabel: input.branchLabel, // Preserve label
487
+ phase: session.currentPhase
473
488
  };
474
489
  session.thoughtHistory.push(thought);
490
+ // 🔧 Action 3: Complexity Routing (Simple Heuristic)
491
+ // If problem statement is short (< 50 chars), suggest simple execution.
492
+ // If long or contains "plan", "complex", "research", suggest full sequential thinking.
493
+ let complexityAnalysis;
494
+ if (session.currentStep === 0) {
495
+ const problemLength = session.problemStatement.length;
496
+ const keywords = ['complex', 'plan', 'research', 'analyze', 'strategy', 'architecture'];
497
+ const isComplex = problemLength > 100 ||
498
+ keywords.some((k) => session.problemStatement.toLowerCase().includes(k));
499
+ complexityAnalysis = isComplex
500
+ ? 'Complexity: HIGH. Recommendation: Use full Sequential Thinking with multiple branches.'
501
+ : 'Complexity: LOW. Recommendation: You might be able to solve this directly with a single tool call or short sequence.';
502
+ // Auto-set style for complex problems
503
+ if (isComplex && session.thinkingStyle === 'Analytical') {
504
+ // Keep Analytical default
505
+ }
506
+ }
507
+ // 🔧 Action 2: Intelligent Tool Recommendation
508
+ const recommendedTools = this.recommendTools(thought.thought, session.currentPhase);
509
+ // 🔧 Action 1+: Guidance based on Style/Phase
510
+ const guidance = this.getGuidance(session.thinkingStyle, session.currentPhase);
511
+ // 🔧 Action 5: Deeper Memory Integration (Async check for sub-problems)
512
+ let relatedMemories = [];
513
+ if (['decomposition', 'replan', 'hypothesis'].includes(thought.thoughtType)) {
514
+ // We await this one to provide immediate context, or we could fire-and-forget
515
+ // For better decision making, immediate is better.
516
+ try {
517
+ const past = await this.queryPastSolutions(thought.thought);
518
+ if (past.length > 0) {
519
+ relatedMemories = past.slice(0, 2); // Top 2 relevant memories
520
+ thought.metadata = { ...thought.metadata, relatedMemories };
521
+ }
522
+ }
523
+ catch (e) {
524
+ console.warn('[Brain] Failed to query memory in addThought:', e);
525
+ }
526
+ }
527
+ // 🔧 Action 3: Suggest router tool if complexity is high
528
+ if (complexityAnalysis && complexityAnalysis.includes('HIGH')) {
529
+ recommendedTools.push({
530
+ toolName: 'decompose',
531
+ confidence: 0.95,
532
+ rationale: 'High complexity detected. Break down the problem first.',
533
+ suggestedInput: { thought: 'Break down the main problem into sub-components' }
534
+ });
535
+ }
475
536
  return {
476
537
  success: true,
477
538
  sessionId: session.sessionId,
@@ -479,11 +540,125 @@ export class SequentialThinkingManager {
479
540
  totalThoughts: session.totalThoughts,
480
541
  status: session.status,
481
542
  thought,
482
- message: `Thought added (${thought.thoughtType})`
543
+ message: `Thought added (${thought.thoughtType}) - Style: ${session.thinkingStyle}, Phase: ${session.currentPhase}`,
544
+ recommendedTools,
545
+ guidance: guidance + (complexityAnalysis ? ` [${complexityAnalysis}]` : ''),
546
+ metadata: { relatedMemories: relatedMemories.length > 0 ? relatedMemories : undefined }
483
547
  };
484
548
  }
549
+ getGuidance(style, phase) {
550
+ let guidance = '';
551
+ // Style-based guidance
552
+ switch (style) {
553
+ case 'Analytical':
554
+ guidance +=
555
+ 'Focus on breaking down the problem into logical components and evaluating data objectively. ';
556
+ break;
557
+ case 'Creative':
558
+ guidance +=
559
+ 'Brainstorm multiple alternative solutions, even those that seem unconventional. Use analogies. ';
560
+ break;
561
+ case 'Critical':
562
+ guidance +=
563
+ 'Look for potential flaws, risks, and assumptions in the current line of reasoning. Challenge everything. ';
564
+ break;
565
+ case 'Emotional':
566
+ guidance +=
567
+ 'Consider the human impact, user experience, and how stakeholders might feel about the solution. ';
568
+ break;
569
+ case 'Optimistic':
570
+ guidance +=
571
+ 'Focus on the benefits, opportunities, and the "best-case" scenario. What makes this succeed? ';
572
+ break;
573
+ case 'Synthesis':
574
+ guidance +=
575
+ 'Combine different perspectives and findings into a coherent and actionable conclusion. ';
576
+ break;
577
+ }
578
+ // Phase-based guidance
579
+ switch (phase) {
580
+ case 'Definition':
581
+ guidance += 'Ensure the problem is clearly defined and constraints are understood.';
582
+ break;
583
+ case 'Exploration':
584
+ guidance += 'Gather information and explore the solution space without committing yet.';
585
+ break;
586
+ case 'Analysis':
587
+ guidance += 'Deeply examine the gathered information and identify patterns or root causes.';
588
+ break;
589
+ case 'Evaluation':
590
+ guidance += 'Score and compare different options based on criteria like risk and impact.';
591
+ break;
592
+ case 'Synthesis':
593
+ guidance += 'Merge ideas and start forming the final solution plan.';
594
+ break;
595
+ case 'Conclusion':
596
+ guidance += 'Finalize the result and ensure it directly addresses the original problem.';
597
+ break;
598
+ }
599
+ return guidance.trim();
600
+ }
601
+ recommendTools(thought, phase) {
602
+ const recommendations = [];
603
+ const text = thought.toLowerCase();
604
+ // Heuristics based on keywords and phase
605
+ if (text.includes('search') ||
606
+ text.includes('find') ||
607
+ text.includes('research') ||
608
+ phase === 'Exploration') {
609
+ recommendations.push({
610
+ toolName: 'web_search',
611
+ confidence: 0.9,
612
+ rationale: 'Thought involves searching for information or is in Exploration phase.',
613
+ suggestedInput: { query: thought }
614
+ });
615
+ recommendations.push({
616
+ toolName: 'vector_search',
617
+ confidence: 0.7,
618
+ rationale: 'Check local semantic memory for related concepts.',
619
+ suggestedInput: { query: thought }
620
+ });
621
+ }
622
+ if (text.includes('save') || text.includes('remember') || text.includes('note')) {
623
+ recommendations.push({
624
+ toolName: 'vector_save',
625
+ confidence: 0.8,
626
+ rationale: 'Thought suggests a need to persist information.',
627
+ suggestedInput: { content: thought }
628
+ });
629
+ }
630
+ if (text.includes('calculate') ||
631
+ text.includes('compute') ||
632
+ text.includes('math') ||
633
+ phase === 'Analysis') {
634
+ recommendations.push({
635
+ toolName: 'compute',
636
+ confidence: 0.8,
637
+ rationale: 'Analytical thoughts often benefit from precise computation.',
638
+ suggestedInput: { expression: '...' }
639
+ });
640
+ }
641
+ if (text.includes('file') || text.includes('write') || phase === 'Conclusion') {
642
+ recommendations.push({
643
+ toolName: 'write_file',
644
+ confidence: 0.7,
645
+ rationale: 'Thought mentions files or is in Conclusion phase, suggesting report generation.',
646
+ suggestedInput: { file_path: '...', content: '...' }
647
+ });
648
+ }
649
+ if (text.includes('list') || text.includes('directory')) {
650
+ recommendations.push({
651
+ toolName: 'list_directory',
652
+ confidence: 0.9,
653
+ rationale: 'Direct mention of directory/listing.',
654
+ suggestedInput: { dir_path: '.' }
655
+ });
656
+ }
657
+ return recommendations;
658
+ }
485
659
  generateOptions(input) {
486
660
  const session = this.getSession(input.sessionId);
661
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
487
662
  if (!session)
488
663
  return { success: false, message: 'Session not found' };
489
664
  // 🔧 NEW: Generate 3-5 distinct options using templates
@@ -492,7 +667,9 @@ export class SequentialThinkingManager {
492
667
  const thought = {
493
668
  id: uuidv4(),
494
669
  stepNumber: session.currentStep,
495
- thought: `GENERATED OPTIONS:\n${options.map((o, i) => `${i + 1}. ${o.label}\n ${o.description}\n Effort: ${o.estimatedEffort}, Risk: ${o.riskLevel}`).join('\n')}`,
670
+ thought: `GENERATED OPTIONS:\n${options
671
+ .map((o, i) => `${i + 1}. ${o.label}\n ${o.description}\n Effort: ${o.estimatedEffort}, Risk: ${o.riskLevel}`)
672
+ .join('\n')}`,
496
673
  thoughtType: 'option_generation',
497
674
  timestamp: new Date().toISOString(),
498
675
  confidence: 75,
@@ -514,6 +691,7 @@ export class SequentialThinkingManager {
514
691
  }
515
692
  evaluateOptions(input) {
516
693
  const session = this.getSession(input.sessionId);
694
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
517
695
  if (!session)
518
696
  return { success: false, message: 'Session not found' };
519
697
  // 🔧 NEW: Evaluate last thought's options
@@ -526,9 +704,10 @@ export class SequentialThinkingManager {
526
704
  totalThoughts: session.totalThoughts,
527
705
  status: session.status,
528
706
  message: 'No options found in last thought. Use generateOptions first.'
707
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
529
708
  };
530
709
  }
531
- const options = lastThought.metadata.options;
710
+ const options = lastThought.metadata.options || [];
532
711
  // 🔧 BUG FIX: Validate array before processing
533
712
  if (!Array.isArray(options) || options.length === 0) {
534
713
  return {
@@ -538,6 +717,7 @@ export class SequentialThinkingManager {
538
717
  totalThoughts: session.totalThoughts,
539
718
  status: session.status,
540
719
  message: 'Invalid options in metadata. Use generateOptions first.'
720
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
541
721
  };
542
722
  }
543
723
  const evaluatedOptions = options.map((opt) => {
@@ -547,7 +727,7 @@ export class SequentialThinkingManager {
547
727
  return {
548
728
  ...opt,
549
729
  scores: { feasibility, impact, risk },
550
- totalScore: (feasibility * 0.4) + (impact * 0.4) + ((1 - risk) * 0.2),
730
+ totalScore: feasibility * 0.4 + impact * 0.4 + (1 - risk) * 0.2,
551
731
  reasoning: `Feasibility: ${(feasibility * 100).toFixed(0)}%, Impact: ${(impact * 100).toFixed(0)}%, Risk: ${(risk * 100).toFixed(0)}%`,
552
732
  confidence: 80,
553
733
  uncertainty: 0.15
@@ -557,7 +737,9 @@ export class SequentialThinkingManager {
557
737
  const thought = {
558
738
  id: uuidv4(),
559
739
  stepNumber: session.currentStep,
560
- thought: `EVALUATED OPTIONS:\n${evaluatedOptions.map((o, i) => `${i + 1}. ${o.label}: ${o.totalScore.toFixed(2)}\n ${o.reasoning}`).join('\n')}`,
740
+ thought: `EVALUATED OPTIONS:\n${evaluatedOptions
741
+ .map((o, i) => `${i + 1}. ${o.label}: ${o.totalScore.toFixed(2)}\n ${o.reasoning}`)
742
+ .join('\n')}`,
561
743
  thoughtType: 'option_evaluation',
562
744
  timestamp: new Date().toISOString(),
563
745
  confidence: 80,
@@ -578,6 +760,8 @@ export class SequentialThinkingManager {
578
760
  };
579
761
  }
580
762
  const best = [...evaluatedOptions].sort((a, b) => b.totalScore - a.totalScore)[0];
763
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
764
+ const bestOption = best;
581
765
  return {
582
766
  success: true,
583
767
  sessionId: session.sessionId,
@@ -585,27 +769,30 @@ export class SequentialThinkingManager {
585
769
  totalThoughts: session.totalThoughts,
586
770
  status: session.status,
587
771
  thought,
588
- message: `Evaluated ${evaluatedOptions.length} options. Best: ${best.label} (${best.totalScore.toFixed(2)})`,
772
+ message: `Evaluated ${evaluatedOptions.length} options. Best: ${bestOption.label} (${bestOption.totalScore.toFixed(2)})`,
589
773
  nextSuggestedActions: ['select_option']
590
774
  };
591
775
  }
592
776
  selectOption(input) {
593
777
  const session = this.getSession(input.sessionId);
778
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
594
779
  if (!session)
595
780
  return { success: false, message: 'Session not found' };
781
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
596
782
  if (!input.optionId)
597
783
  return { success: false, message: 'optionId required' };
598
- const selected = session.thoughtHistory.find(t => t.id === input.optionId);
784
+ const selected = session.thoughtHistory.find((t) => t.id === input.optionId);
785
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
599
786
  if (!selected)
600
787
  return { success: false, message: 'Option not found' };
601
788
  // 🔧 NEW: Enhanced selection with evaluation data
602
789
  const evalThought = session.thoughtHistory
603
- .filter(t => t.thoughtType === 'option_evaluation')
790
+ .filter((t) => t.thoughtType === 'option_evaluation')
604
791
  .slice(-1)[0];
605
792
  let evalData = null;
606
793
  if (evalThought?.metadata?.evaluatedOptions) {
607
794
  const options = evalThought.metadata.evaluatedOptions;
608
- evalData = options.find((o) => o.id === input.optionId);
795
+ evalData = options.find((o) => o.id === input.optionId) || null;
609
796
  }
610
797
  const confidence = evalData?.confidence || 85;
611
798
  const uncertainty = evalData?.uncertainty || 0.15;
@@ -659,7 +846,9 @@ export class SequentialThinkingManager {
659
846
  };
660
847
  session.thoughtHistory.push(thought);
661
848
  if (input.thought && input.thought.length > 50) {
662
- vectorMemory.add(`Reflexion on ${session.problemStatement}: ${input.thought}`, { sessionId: session.sessionId });
849
+ vectorMemory.add(`Reflexion on ${session.problemStatement}: ${input.thought}`, {
850
+ sessionId: session.sessionId
851
+ });
663
852
  }
664
853
  return {
665
854
  success: true,
@@ -707,16 +896,21 @@ export class SequentialThinkingManager {
707
896
  plan = {
708
897
  planId: 'auto-' + uuidv4(),
709
898
  name: 'Auto Plan',
710
- tasks: [{
899
+ tasks: [
900
+ {
711
901
  id: 't1',
712
902
  name: 'Auto Echo',
713
903
  toolName: 'echo',
714
904
  toolInput: { text: 'Running fallback due to invalid plan format.' },
715
905
  dependencies: []
716
- }]
906
+ }
907
+ ]
717
908
  };
718
909
  }
719
- const execResult = await orchestratorManager.process({ action: 'execute_plan', plan: plan });
910
+ const execResult = await orchestratorManager.process({
911
+ action: 'execute_plan',
912
+ plan: plan
913
+ });
720
914
  // 🔧 NEW: Learn from execution outcome
721
915
  await this.analyzeExecutionOutcome(session, execResult);
722
916
  await this.process({
@@ -733,7 +927,9 @@ export class SequentialThinkingManager {
733
927
  currentStep: session.currentStep,
734
928
  totalThoughts: session.totalThoughts,
735
929
  status: session.status,
736
- message: execResult.success ? `Execution Success. Reflexion triggered.` : `Execution Failed: ${execResult.message}. Reflexion triggered.`,
930
+ message: execResult.success
931
+ ? `Execution Success. Reflexion triggered.`
932
+ : `Execution Failed: ${execResult.message}. Reflexion triggered.`,
737
933
  executionResult: execResult.result,
738
934
  metadata: { validationErrors: execResult.validationErrors }
739
935
  };
@@ -754,7 +950,9 @@ export class SequentialThinkingManager {
754
950
  return this.sessions.get(id);
755
951
  }
756
952
  getLastThoughtId(session) {
757
- return session.thoughtHistory.length > 0 ? session.thoughtHistory[session.thoughtHistory.length - 1].id : undefined;
953
+ return session.thoughtHistory.length > 0
954
+ ? session.thoughtHistory[session.thoughtHistory.length - 1].id
955
+ : undefined;
758
956
  }
759
957
  // 🔧 NEW: Helper methods for ToT implementation
760
958
  generateThoughtOptions(session, context) {
@@ -792,22 +990,25 @@ export class SequentialThinkingManager {
792
990
  // 🔧 BUG FIX: Add null safety
793
991
  if (!opt || typeof opt !== 'object')
794
992
  return 0.5;
993
+ const effort = opt.estimatedEffort;
795
994
  const effortMap = { low: 0.9, medium: 0.6, high: 0.3 };
796
- return effortMap[opt.estimatedEffort] || 0.5;
995
+ return effortMap[effort] || 0.5;
797
996
  }
798
997
  estimateImpact(opt) {
799
998
  // 🔧 BUG FIX: Add null safety
800
999
  if (!opt || typeof opt !== 'object')
801
1000
  return 0.5;
1001
+ const risk = opt.riskLevel;
802
1002
  const riskMap = { low: 0.4, medium: 0.7, high: 0.9 };
803
- return riskMap[opt.riskLevel] || 0.5;
1003
+ return riskMap[risk] || 0.5;
804
1004
  }
805
1005
  estimateRisk(opt) {
806
1006
  // 🔧 BUG FIX: Add null safety
807
1007
  if (!opt || typeof opt !== 'object')
808
1008
  return 0.5;
1009
+ const risk = opt.riskLevel;
809
1010
  const riskMap = { low: 0.1, medium: 0.4, high: 0.7 };
810
- return riskMap[opt.riskLevel] || 0.5;
1011
+ return riskMap[risk] || 0.5;
811
1012
  }
812
1013
  // 🔧 NEW: Learning System methods
813
1014
  async analyzeExecutionOutcome(session, result) {
@@ -846,7 +1047,9 @@ export class SequentialThinkingManager {
846
1047
  }
847
1048
  else {
848
1049
  const errorMsg = result.message || result.result?.errors?.[0]?.error || '';
849
- if (errorMsg.includes('fetch') || errorMsg.includes('network') || errorMsg.includes('ECONNREFUSED')) {
1050
+ if (errorMsg.includes('fetch') ||
1051
+ errorMsg.includes('network') ||
1052
+ errorMsg.includes('ECONNREFUSED')) {
850
1053
  patterns.push('network-failure');
851
1054
  }
852
1055
  if (errorMsg.includes('timeout') || errorMsg.includes('timed out')) {
@@ -893,7 +1096,7 @@ export class SequentialThinkingManager {
893
1096
  const query = `Similar problems to: ${problem}`;
894
1097
  try {
895
1098
  const results = await vectorMemory.search(query, 5);
896
- return results.map(r => ({
1099
+ return results.map((r) => ({
897
1100
  problem: r.item.content,
898
1101
  solution: r.item.metadata,
899
1102
  relevance: r.score || 0.5,
@@ -906,10 +1109,18 @@ export class SequentialThinkingManager {
906
1109
  return [];
907
1110
  }
908
1111
  }
909
- createBranch(input) { return this.addThought(input); }
910
- reviseThought(input) { return this.addThought({ ...input, thoughtType: 'revision' }); }
911
- setHypothesis(input) { return this.addThought({ ...input, thoughtType: 'hypothesis' }); }
912
- verifyHypothesis(input) { return this.addThought({ ...input, thoughtType: 'verification' }); }
1112
+ createBranch(input) {
1113
+ return this.addThought(input);
1114
+ }
1115
+ reviseThought(input) {
1116
+ return this.addThought({ ...input, thoughtType: 'revision' });
1117
+ }
1118
+ setHypothesis(input) {
1119
+ return this.addThought({ ...input, thoughtType: 'hypothesis' });
1120
+ }
1121
+ verifyHypothesis(input) {
1122
+ return this.addThought({ ...input, thoughtType: 'verification' });
1123
+ }
913
1124
  conclude(input) {
914
1125
  const session = this.getSession(input.sessionId);
915
1126
  if (session) {