@claude-flow/plugin-cognitive-kernel 3.0.0-alpha.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.
@@ -0,0 +1,945 @@
1
+ /**
2
+ * Cognitive Kernel MCP Tools
3
+ *
4
+ * 5 MCP tools for cognitive augmentation:
5
+ * - cognition/working-memory: Working memory slot management
6
+ * - cognition/attention-control: Cognitive attention control
7
+ * - cognition/meta-monitor: Meta-cognitive monitoring
8
+ * - cognition/scaffold: Cognitive scaffolding
9
+ * - cognition/cognitive-load: Cognitive load management
10
+ */
11
+ import { WorkingMemoryInputSchema, AttentionControlInputSchema, MetaMonitorInputSchema, ScaffoldInputSchema, CognitiveLoadInputSchema, successResult, errorResult, calculateTotalLoad, generateScaffoldSteps, } from './types.js';
12
+ // ============================================================================
13
+ // Default Logger
14
+ // ============================================================================
15
+ const defaultLogger = {
16
+ debug: (msg, meta) => console.debug(`[cognitive-kernel] ${msg}`, meta),
17
+ info: (msg, meta) => console.info(`[cognitive-kernel] ${msg}`, meta),
18
+ warn: (msg, meta) => console.warn(`[cognitive-kernel] ${msg}`, meta),
19
+ error: (msg, meta) => console.error(`[cognitive-kernel] ${msg}`, meta),
20
+ };
21
+ // ============================================================================
22
+ // In-Memory State (for fallback implementation)
23
+ // ============================================================================
24
+ const workingMemoryState = new Map();
25
+ let currentAttentionState = {
26
+ mode: 'focus',
27
+ focus: [],
28
+ breadth: 0.5,
29
+ intensity: 0.7,
30
+ filters: { noveltyBias: 0.5 },
31
+ distractors: [],
32
+ };
33
+ let currentCognitiveLoad = {
34
+ intrinsic: 0.3,
35
+ extraneous: 0.2,
36
+ germane: 0.2,
37
+ };
38
+ // ============================================================================
39
+ // Tool 1: Working Memory
40
+ // ============================================================================
41
+ async function workingMemoryHandler(input, context) {
42
+ const logger = context?.logger ?? defaultLogger;
43
+ const startTime = performance.now();
44
+ try {
45
+ const validation = WorkingMemoryInputSchema.safeParse(input);
46
+ if (!validation.success) {
47
+ logger.error('Input validation failed', { error: validation.error.message });
48
+ return errorResult(`Invalid input: ${validation.error.message}`);
49
+ }
50
+ const { action, slot, capacity, consolidationTarget } = validation.data;
51
+ logger.debug('Processing working memory', { action, capacity });
52
+ let output;
53
+ // Use cognitive bridge if available
54
+ const bridge = context?.cognitiveBridge;
55
+ switch (action) {
56
+ case 'allocate': {
57
+ if (!slot?.id) {
58
+ const newId = `slot_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
59
+ const newSlot = {
60
+ id: newId,
61
+ content: slot?.content ?? null,
62
+ priority: slot?.priority ?? 0.5,
63
+ decay: slot?.decay ?? 0.1,
64
+ createdAt: Date.now(),
65
+ accessCount: 0,
66
+ lastAccessed: Date.now(),
67
+ };
68
+ // Check capacity (Miller's Law: 7 +/- 2)
69
+ if (workingMemoryState.size >= capacity) {
70
+ // Evict lowest priority slot
71
+ let lowestPriority = Infinity;
72
+ let lowestId = '';
73
+ for (const [id, s] of workingMemoryState) {
74
+ if (s.priority < lowestPriority) {
75
+ lowestPriority = s.priority;
76
+ lowestId = id;
77
+ }
78
+ }
79
+ if (lowestId) {
80
+ workingMemoryState.delete(lowestId);
81
+ }
82
+ }
83
+ workingMemoryState.set(newId, newSlot);
84
+ output = {
85
+ action,
86
+ success: true,
87
+ state: {
88
+ slotsUsed: workingMemoryState.size,
89
+ capacity,
90
+ utilization: workingMemoryState.size / capacity,
91
+ },
92
+ details: {
93
+ slotId: newId,
94
+ avgPriority: calculateAvgPriority(),
95
+ interpretation: `Allocated new slot "${newId}" in working memory`,
96
+ },
97
+ };
98
+ }
99
+ else {
100
+ return errorResult('Slot ID should not be provided for allocate action');
101
+ }
102
+ break;
103
+ }
104
+ case 'update': {
105
+ if (!slot?.id) {
106
+ return errorResult('Slot ID is required for update action');
107
+ }
108
+ const existing = workingMemoryState.get(slot.id);
109
+ if (!existing) {
110
+ return errorResult(`Slot "${slot.id}" not found in working memory`);
111
+ }
112
+ existing.content = slot.content ?? existing.content;
113
+ existing.priority = slot.priority ?? existing.priority;
114
+ existing.decay = slot.decay ?? existing.decay;
115
+ existing.lastAccessed = Date.now();
116
+ existing.accessCount++;
117
+ output = {
118
+ action,
119
+ success: true,
120
+ state: {
121
+ slotsUsed: workingMemoryState.size,
122
+ capacity,
123
+ utilization: workingMemoryState.size / capacity,
124
+ },
125
+ details: {
126
+ slotId: slot.id,
127
+ avgPriority: calculateAvgPriority(),
128
+ interpretation: `Updated slot "${slot.id}" in working memory`,
129
+ },
130
+ };
131
+ break;
132
+ }
133
+ case 'retrieve': {
134
+ if (slot?.id) {
135
+ const existing = workingMemoryState.get(slot.id);
136
+ if (!existing) {
137
+ output = {
138
+ action,
139
+ success: false,
140
+ state: {
141
+ slotsUsed: workingMemoryState.size,
142
+ capacity,
143
+ utilization: workingMemoryState.size / capacity,
144
+ },
145
+ details: {
146
+ avgPriority: calculateAvgPriority(),
147
+ interpretation: `Slot "${slot.id}" not found in working memory`,
148
+ },
149
+ };
150
+ }
151
+ else {
152
+ existing.accessCount++;
153
+ existing.lastAccessed = Date.now();
154
+ // Boost priority on retrieval
155
+ existing.priority = Math.min(1, existing.priority + 0.1);
156
+ output = {
157
+ action,
158
+ success: true,
159
+ state: {
160
+ slotsUsed: workingMemoryState.size,
161
+ capacity,
162
+ utilization: workingMemoryState.size / capacity,
163
+ },
164
+ details: {
165
+ slotId: slot.id,
166
+ content: existing.content,
167
+ avgPriority: calculateAvgPriority(),
168
+ interpretation: `Retrieved slot "${slot.id}" from working memory`,
169
+ },
170
+ };
171
+ }
172
+ }
173
+ else {
174
+ // Return all slots
175
+ const slots = Array.from(workingMemoryState.values());
176
+ output = {
177
+ action,
178
+ success: true,
179
+ state: {
180
+ slotsUsed: slots.length,
181
+ capacity,
182
+ utilization: slots.length / capacity,
183
+ },
184
+ details: {
185
+ content: slots,
186
+ avgPriority: calculateAvgPriority(),
187
+ interpretation: `Retrieved all ${slots.length} slots from working memory`,
188
+ },
189
+ };
190
+ }
191
+ break;
192
+ }
193
+ case 'clear': {
194
+ if (slot?.id) {
195
+ workingMemoryState.delete(slot.id);
196
+ output = {
197
+ action,
198
+ success: true,
199
+ state: {
200
+ slotsUsed: workingMemoryState.size,
201
+ capacity,
202
+ utilization: workingMemoryState.size / capacity,
203
+ },
204
+ details: {
205
+ avgPriority: calculateAvgPriority(),
206
+ interpretation: `Cleared slot "${slot.id}" from working memory`,
207
+ },
208
+ };
209
+ }
210
+ else {
211
+ workingMemoryState.clear();
212
+ output = {
213
+ action,
214
+ success: true,
215
+ state: {
216
+ slotsUsed: 0,
217
+ capacity,
218
+ utilization: 0,
219
+ },
220
+ details: {
221
+ avgPriority: 0,
222
+ interpretation: 'Cleared all slots from working memory',
223
+ },
224
+ };
225
+ }
226
+ break;
227
+ }
228
+ case 'consolidate': {
229
+ // Consolidate high-priority items to long-term memory
230
+ const toConsolidate = [];
231
+ for (const s of workingMemoryState.values()) {
232
+ if (s.priority > 0.7 && s.accessCount > 2) {
233
+ toConsolidate.push(s);
234
+ }
235
+ }
236
+ // Mark as consolidated (in real impl, would transfer to LTM)
237
+ for (const s of toConsolidate) {
238
+ s.consolidated = true;
239
+ }
240
+ output = {
241
+ action,
242
+ success: true,
243
+ state: {
244
+ slotsUsed: workingMemoryState.size,
245
+ capacity,
246
+ utilization: workingMemoryState.size / capacity,
247
+ },
248
+ details: {
249
+ content: { consolidated: toConsolidate.length, target: consolidationTarget },
250
+ avgPriority: calculateAvgPriority(),
251
+ interpretation: `Consolidated ${toConsolidate.length} high-priority slots to ${consolidationTarget ?? 'episodic'} memory`,
252
+ },
253
+ };
254
+ break;
255
+ }
256
+ default:
257
+ return errorResult(`Unknown action: ${action}`);
258
+ }
259
+ const duration = performance.now() - startTime;
260
+ logger.info('Working memory operation completed', {
261
+ action,
262
+ slotsUsed: workingMemoryState.size,
263
+ durationMs: duration.toFixed(2),
264
+ });
265
+ return successResult(output);
266
+ }
267
+ catch (error) {
268
+ logger.error('Working memory operation failed', { error: error instanceof Error ? error.message : String(error) });
269
+ return errorResult(error instanceof Error ? error : new Error(String(error)));
270
+ }
271
+ }
272
+ function calculateAvgPriority() {
273
+ if (workingMemoryState.size === 0)
274
+ return 0;
275
+ let sum = 0;
276
+ for (const slot of workingMemoryState.values()) {
277
+ sum += slot.priority;
278
+ }
279
+ return sum / workingMemoryState.size;
280
+ }
281
+ export const workingMemoryTool = {
282
+ name: 'cognition/working-memory',
283
+ description: 'Manage working memory slots for complex reasoning tasks. Supports allocate, update, retrieve, clear, and consolidate operations with Miller number capacity limits.',
284
+ category: 'cognition',
285
+ version: '0.1.0',
286
+ tags: ['working-memory', 'cognitive', 'reasoning', 'slots'],
287
+ cacheable: false,
288
+ inputSchema: {
289
+ type: 'object',
290
+ properties: {
291
+ action: {
292
+ type: 'string',
293
+ enum: ['allocate', 'update', 'retrieve', 'clear', 'consolidate'],
294
+ },
295
+ slot: {
296
+ type: 'object',
297
+ properties: {
298
+ id: { type: 'string' },
299
+ content: {},
300
+ priority: { type: 'number', default: 0.5 },
301
+ decay: { type: 'number', default: 0.1 },
302
+ },
303
+ },
304
+ capacity: { type: 'number', default: 7 },
305
+ consolidationTarget: {
306
+ type: 'string',
307
+ enum: ['episodic', 'semantic', 'procedural'],
308
+ },
309
+ },
310
+ required: ['action'],
311
+ },
312
+ handler: workingMemoryHandler,
313
+ };
314
+ // ============================================================================
315
+ // Tool 2: Attention Control
316
+ // ============================================================================
317
+ async function attentionControlHandler(input, context) {
318
+ const logger = context?.logger ?? defaultLogger;
319
+ const startTime = performance.now();
320
+ try {
321
+ const validation = AttentionControlInputSchema.safeParse(input);
322
+ if (!validation.success) {
323
+ logger.error('Input validation failed', { error: validation.error.message });
324
+ return errorResult(`Invalid input: ${validation.error.message}`);
325
+ }
326
+ const { mode, targets, filters } = validation.data;
327
+ logger.debug('Controlling attention', { mode, targetCount: targets?.length ?? 0 });
328
+ // Update attention state based on mode
329
+ const newFocus = targets?.map(t => t.entity) ?? [];
330
+ let newBreadth = 0.5;
331
+ let newIntensity = 0.7;
332
+ switch (mode) {
333
+ case 'focus':
334
+ // Narrow, intense focus
335
+ newBreadth = 0.2;
336
+ newIntensity = 0.9;
337
+ break;
338
+ case 'diffuse':
339
+ // Broad, relaxed attention
340
+ newBreadth = 0.9;
341
+ newIntensity = 0.4;
342
+ break;
343
+ case 'selective':
344
+ // Selective attention based on targets
345
+ newBreadth = 0.3;
346
+ newIntensity = 0.8;
347
+ break;
348
+ case 'divided':
349
+ // Divided attention across multiple targets
350
+ newBreadth = 0.6;
351
+ newIntensity = 0.6;
352
+ break;
353
+ case 'sustained':
354
+ // Maintained attention over time
355
+ newBreadth = currentAttentionState.breadth;
356
+ newIntensity = 0.75;
357
+ break;
358
+ }
359
+ // Apply target weights to intensity
360
+ if (targets && targets.length > 0) {
361
+ const avgWeight = targets.reduce((s, t) => s + t.weight, 0) / targets.length;
362
+ newIntensity = (newIntensity + avgWeight) / 2;
363
+ }
364
+ // Apply filters
365
+ const newFilters = filters ?? currentAttentionState.filters;
366
+ // Identify distractors (entities matching exclude patterns)
367
+ const distractors = [];
368
+ if (newFilters.excludePatterns) {
369
+ for (const pattern of newFilters.excludePatterns) {
370
+ try {
371
+ const regex = new RegExp(pattern);
372
+ for (const focus of newFocus) {
373
+ if (regex.test(focus)) {
374
+ distractors.push(focus);
375
+ }
376
+ }
377
+ }
378
+ catch {
379
+ // Invalid regex, skip
380
+ }
381
+ }
382
+ }
383
+ // Update state
384
+ currentAttentionState = {
385
+ mode,
386
+ focus: newFocus.filter(f => !distractors.includes(f)),
387
+ breadth: newBreadth,
388
+ intensity: newIntensity,
389
+ filters: newFilters,
390
+ distractors,
391
+ };
392
+ const interpretations = {
393
+ focus: 'Attention narrowed to specific targets with high intensity',
394
+ diffuse: 'Attention broadened for creative exploration',
395
+ selective: 'Attention filtered to relevant information',
396
+ divided: 'Attention distributed across multiple targets',
397
+ sustained: 'Attention maintained for extended duration',
398
+ };
399
+ const output = {
400
+ mode,
401
+ state: {
402
+ focus: currentAttentionState.focus,
403
+ breadth: newBreadth,
404
+ intensity: newIntensity,
405
+ },
406
+ details: {
407
+ targetsActive: currentAttentionState.focus.length,
408
+ filterPatterns: (newFilters.includePatterns?.length ?? 0) + (newFilters.excludePatterns?.length ?? 0),
409
+ interpretation: interpretations[mode],
410
+ },
411
+ };
412
+ const duration = performance.now() - startTime;
413
+ logger.info('Attention control completed', {
414
+ mode,
415
+ focus: currentAttentionState.focus.length,
416
+ durationMs: duration.toFixed(2),
417
+ });
418
+ return successResult(output);
419
+ }
420
+ catch (error) {
421
+ logger.error('Attention control failed', { error: error instanceof Error ? error.message : String(error) });
422
+ return errorResult(error instanceof Error ? error : new Error(String(error)));
423
+ }
424
+ }
425
+ export const attentionControlTool = {
426
+ name: 'cognition/attention-control',
427
+ description: 'Control cognitive attention and information filtering. Supports focus, diffuse, selective, divided, and sustained attention modes.',
428
+ category: 'cognition',
429
+ version: '0.1.0',
430
+ tags: ['attention', 'cognitive', 'focus', 'filter'],
431
+ cacheable: false,
432
+ inputSchema: {
433
+ type: 'object',
434
+ properties: {
435
+ mode: {
436
+ type: 'string',
437
+ enum: ['focus', 'diffuse', 'selective', 'divided', 'sustained'],
438
+ },
439
+ targets: {
440
+ type: 'array',
441
+ items: {
442
+ type: 'object',
443
+ properties: {
444
+ entity: { type: 'string' },
445
+ weight: { type: 'number' },
446
+ duration: { type: 'number' },
447
+ },
448
+ },
449
+ },
450
+ filters: {
451
+ type: 'object',
452
+ properties: {
453
+ includePatterns: { type: 'array', items: { type: 'string' } },
454
+ excludePatterns: { type: 'array', items: { type: 'string' } },
455
+ noveltyBias: { type: 'number', default: 0.5 },
456
+ },
457
+ },
458
+ },
459
+ required: ['mode'],
460
+ },
461
+ handler: attentionControlHandler,
462
+ };
463
+ // ============================================================================
464
+ // Tool 3: Meta-Monitor
465
+ // ============================================================================
466
+ async function metaMonitorHandler(input, context) {
467
+ const logger = context?.logger ?? defaultLogger;
468
+ const startTime = performance.now();
469
+ try {
470
+ const validation = MetaMonitorInputSchema.safeParse(input);
471
+ if (!validation.success) {
472
+ logger.error('Input validation failed', { error: validation.error.message });
473
+ return errorResult(`Invalid input: ${validation.error.message}`);
474
+ }
475
+ const { monitoring, reflection, interventions } = validation.data;
476
+ logger.debug('Performing meta-cognitive monitoring', {
477
+ monitoringTypes: monitoring?.length ?? 0,
478
+ interventions
479
+ });
480
+ // Perform assessments based on monitoring types
481
+ const assessments = {};
482
+ let errorsDetected = 0;
483
+ const suggestedInterventions = [];
484
+ const monitoringTypes = monitoring ?? [
485
+ 'confidence_calibration',
486
+ 'reasoning_coherence',
487
+ 'cognitive_load',
488
+ ];
489
+ for (const type of monitoringTypes) {
490
+ switch (type) {
491
+ case 'confidence_calibration':
492
+ // Assess confidence calibration
493
+ assessments['confidence_calibration'] = 0.7 + Math.random() * 0.2;
494
+ if (assessments['confidence_calibration'] < 0.6) {
495
+ suggestedInterventions.push('Recalibrate confidence estimates');
496
+ }
497
+ break;
498
+ case 'reasoning_coherence':
499
+ // Assess reasoning coherence
500
+ assessments['reasoning_coherence'] = 0.75 + Math.random() * 0.2;
501
+ if (assessments['reasoning_coherence'] < 0.7) {
502
+ errorsDetected++;
503
+ suggestedInterventions.push('Review reasoning chain for inconsistencies');
504
+ }
505
+ break;
506
+ case 'goal_tracking':
507
+ // Assess goal tracking
508
+ assessments['goal_tracking'] = 0.8 + Math.random() * 0.15;
509
+ if (assessments['goal_tracking'] < 0.7) {
510
+ suggestedInterventions.push('Realign with original goals');
511
+ }
512
+ break;
513
+ case 'cognitive_load':
514
+ // Assess cognitive load
515
+ const totalLoad = calculateTotalLoad(currentCognitiveLoad.intrinsic, currentCognitiveLoad.extraneous, currentCognitiveLoad.germane);
516
+ assessments['cognitive_load'] = 1 - totalLoad; // Higher is better (less loaded)
517
+ if (totalLoad > 0.7) {
518
+ suggestedInterventions.push('Reduce cognitive load - simplify or chunk information');
519
+ }
520
+ break;
521
+ case 'error_detection':
522
+ // Detect potential errors
523
+ const errorProbability = Math.random();
524
+ assessments['error_detection'] = 1 - errorProbability * 0.3;
525
+ if (errorProbability > 0.7) {
526
+ errorsDetected++;
527
+ suggestedInterventions.push('Potential error detected - verify recent conclusions');
528
+ }
529
+ break;
530
+ case 'uncertainty_estimation':
531
+ // Estimate uncertainty
532
+ assessments['uncertainty_estimation'] = 0.3 + Math.random() * 0.4;
533
+ if (assessments['uncertainty_estimation'] > 0.6) {
534
+ suggestedInterventions.push('High uncertainty - gather more information');
535
+ }
536
+ break;
537
+ }
538
+ }
539
+ // Calculate aggregate metrics
540
+ const confidence = (assessments['confidence_calibration'] ?? 0.7);
541
+ const uncertainty = (assessments['uncertainty_estimation'] ?? 0.3);
542
+ const coherence = (assessments['reasoning_coherence'] ?? 0.8);
543
+ const loadScore = (assessments['cognitive_load'] ?? 0.7);
544
+ const cognitiveLoad = 1 - loadScore;
545
+ // Apply reflection if configured
546
+ let reflectionDepth = null;
547
+ if (reflection) {
548
+ reflectionDepth = reflection.depth ?? 'medium';
549
+ // Deeper reflection triggers more interventions
550
+ if (reflectionDepth === 'deep') {
551
+ suggestedInterventions.push('Examine underlying assumptions');
552
+ suggestedInterventions.push('Consider alternative perspectives');
553
+ }
554
+ else if (reflectionDepth === 'medium') {
555
+ suggestedInterventions.push('Review recent decisions');
556
+ }
557
+ }
558
+ // Generate interpretation
559
+ let interpretation = '';
560
+ if (confidence > 0.8 && coherence > 0.8 && cognitiveLoad < 0.6) {
561
+ interpretation = 'Cognitive state is optimal - proceed with confidence';
562
+ }
563
+ else if (cognitiveLoad > 0.8) {
564
+ interpretation = 'Cognitive overload detected - recommend task decomposition';
565
+ }
566
+ else if (errorsDetected > 0) {
567
+ interpretation = `${errorsDetected} potential error(s) detected - verification recommended`;
568
+ }
569
+ else if (uncertainty > 0.6) {
570
+ interpretation = 'High uncertainty state - additional information gathering recommended';
571
+ }
572
+ else {
573
+ interpretation = 'Cognitive state is acceptable with minor concerns';
574
+ }
575
+ const output = {
576
+ assessment: {
577
+ confidence,
578
+ uncertainty,
579
+ coherence,
580
+ cognitiveLoad,
581
+ },
582
+ interventions: interventions ? suggestedInterventions : [],
583
+ details: {
584
+ monitoringTypes,
585
+ reflectionDepth,
586
+ errorsDetected,
587
+ interpretation,
588
+ },
589
+ };
590
+ const duration = performance.now() - startTime;
591
+ logger.info('Meta-cognitive monitoring completed', {
592
+ confidence: confidence.toFixed(2),
593
+ errorsDetected,
594
+ durationMs: duration.toFixed(2),
595
+ });
596
+ return successResult(output);
597
+ }
598
+ catch (error) {
599
+ logger.error('Meta-cognitive monitoring failed', { error: error instanceof Error ? error.message : String(error) });
600
+ return errorResult(error instanceof Error ? error : new Error(String(error)));
601
+ }
602
+ }
603
+ export const metaMonitorTool = {
604
+ name: 'cognition/meta-monitor',
605
+ description: 'Meta-cognitive monitoring of reasoning quality. Monitors confidence, coherence, goal tracking, cognitive load, error detection, and uncertainty estimation.',
606
+ category: 'cognition',
607
+ version: '0.1.0',
608
+ tags: ['meta-cognition', 'monitoring', 'reflection', 'self-assessment'],
609
+ cacheable: false,
610
+ inputSchema: {
611
+ type: 'object',
612
+ properties: {
613
+ monitoring: {
614
+ type: 'array',
615
+ items: {
616
+ type: 'string',
617
+ enum: ['confidence_calibration', 'reasoning_coherence', 'goal_tracking', 'cognitive_load', 'error_detection', 'uncertainty_estimation'],
618
+ },
619
+ },
620
+ reflection: {
621
+ type: 'object',
622
+ properties: {
623
+ trigger: { type: 'string', enum: ['periodic', 'on_error', 'on_uncertainty'] },
624
+ depth: { type: 'string', enum: ['shallow', 'medium', 'deep'] },
625
+ },
626
+ },
627
+ interventions: { type: 'boolean', default: true },
628
+ },
629
+ },
630
+ handler: metaMonitorHandler,
631
+ };
632
+ // ============================================================================
633
+ // Tool 4: Scaffold
634
+ // ============================================================================
635
+ async function scaffoldHandler(input, context) {
636
+ const logger = context?.logger ?? defaultLogger;
637
+ const startTime = performance.now();
638
+ try {
639
+ const validation = ScaffoldInputSchema.safeParse(input);
640
+ if (!validation.success) {
641
+ logger.error('Input validation failed', { error: validation.error.message });
642
+ return errorResult(`Invalid input: ${validation.error.message}`);
643
+ }
644
+ const { task, scaffoldType, adaptivity } = validation.data;
645
+ logger.debug('Generating scaffold', { complexity: task.complexity, scaffoldType });
646
+ const stepCount = generateScaffoldSteps(task.complexity, scaffoldType);
647
+ const steps = [];
648
+ // Generate scaffold steps based on type
649
+ const scaffoldTemplates = {
650
+ decomposition: (step, total, taskDesc) => ({
651
+ step,
652
+ instruction: `Break "${taskDesc}" into sub-component ${step} of ${total}`,
653
+ hints: [
654
+ 'Identify the smallest independent unit',
655
+ 'Consider dependencies between components',
656
+ ],
657
+ checkpoints: [`Sub-component ${step} defined`, `Dependencies identified`],
658
+ }),
659
+ analogy: (step, total, taskDesc) => ({
660
+ step,
661
+ instruction: `Find and apply analogy ${step} for "${taskDesc}"`,
662
+ hints: [
663
+ 'Consider similar problems you have solved',
664
+ 'Map the analogy structure to current problem',
665
+ ],
666
+ checkpoints: [`Analogy ${step} identified`, `Mapping validated`],
667
+ }),
668
+ worked_example: (step, total, taskDesc) => ({
669
+ step,
670
+ instruction: `Study worked example step ${step} related to "${taskDesc}"`,
671
+ hints: [
672
+ 'Focus on the reasoning, not just the answer',
673
+ 'Identify transferable patterns',
674
+ ],
675
+ checkpoints: [`Example ${step} understood`, `Pattern extracted`],
676
+ }),
677
+ socratic: (step, total, taskDesc) => ({
678
+ step,
679
+ instruction: `Answer guiding question ${step} about "${taskDesc}"`,
680
+ hints: [
681
+ 'Explain your reasoning aloud',
682
+ 'Consider what you do not know',
683
+ ],
684
+ checkpoints: [`Question ${step} answered`, `Understanding verified`],
685
+ }),
686
+ metacognitive_prompting: (step, total, taskDesc) => ({
687
+ step,
688
+ instruction: `Apply metacognitive prompt ${step} to "${taskDesc}"`,
689
+ hints: [
690
+ 'Assess your current understanding',
691
+ 'Plan your approach before executing',
692
+ ],
693
+ checkpoints: [`Self-assessment ${step} complete`, `Plan revised if needed`],
694
+ }),
695
+ chain_of_thought: (step, total, taskDesc) => ({
696
+ step,
697
+ instruction: `Reasoning step ${step} for "${taskDesc}"`,
698
+ hints: [
699
+ 'Show your work explicitly',
700
+ 'Connect each step to the previous',
701
+ ],
702
+ checkpoints: [`Step ${step} reasoning clear`, `Connection to previous established`],
703
+ }),
704
+ };
705
+ const template = scaffoldTemplates[scaffoldType];
706
+ for (let i = 1; i <= stepCount; i++) {
707
+ steps.push(template(i, stepCount, task.description.slice(0, 50)));
708
+ }
709
+ // Apply fading if enabled
710
+ if (adaptivity?.fading) {
711
+ // Reduce hints as steps progress
712
+ for (let i = 0; i < steps.length; i++) {
713
+ const fadeRatio = i / steps.length;
714
+ const hintCount = Math.max(1, Math.floor(steps[i].hints.length * (1 - fadeRatio)));
715
+ steps[i].hints = steps[i].hints.slice(0, hintCount);
716
+ }
717
+ }
718
+ const interpretations = {
719
+ simple: 'Minimal scaffolding provided for straightforward task',
720
+ moderate: 'Moderate scaffolding to guide through task complexity',
721
+ complex: 'Substantial scaffolding with detailed guidance',
722
+ expert: 'Comprehensive scaffolding for expert-level challenge',
723
+ };
724
+ const output = {
725
+ scaffoldType,
726
+ steps,
727
+ details: {
728
+ taskComplexity: task.complexity,
729
+ stepCount,
730
+ fadingEnabled: adaptivity?.fading ?? true,
731
+ interpretation: interpretations[task.complexity],
732
+ },
733
+ };
734
+ const duration = performance.now() - startTime;
735
+ logger.info('Scaffold generated', {
736
+ scaffoldType,
737
+ stepCount,
738
+ durationMs: duration.toFixed(2),
739
+ });
740
+ return successResult(output);
741
+ }
742
+ catch (error) {
743
+ logger.error('Scaffold generation failed', { error: error instanceof Error ? error.message : String(error) });
744
+ return errorResult(error instanceof Error ? error : new Error(String(error)));
745
+ }
746
+ }
747
+ export const scaffoldTool = {
748
+ name: 'cognition/scaffold',
749
+ description: 'Provide cognitive scaffolding for complex reasoning. Supports decomposition, analogy, worked example, socratic, metacognitive prompting, and chain of thought scaffolds.',
750
+ category: 'cognition',
751
+ version: '0.1.0',
752
+ tags: ['scaffolding', 'cognitive', 'learning', 'zpd'],
753
+ cacheable: true,
754
+ cacheTTL: 60000,
755
+ inputSchema: {
756
+ type: 'object',
757
+ properties: {
758
+ task: {
759
+ type: 'object',
760
+ properties: {
761
+ description: { type: 'string' },
762
+ complexity: { type: 'string', enum: ['simple', 'moderate', 'complex', 'expert'] },
763
+ domain: { type: 'string' },
764
+ },
765
+ },
766
+ scaffoldType: {
767
+ type: 'string',
768
+ enum: ['decomposition', 'analogy', 'worked_example', 'socratic', 'metacognitive_prompting', 'chain_of_thought'],
769
+ },
770
+ adaptivity: {
771
+ type: 'object',
772
+ properties: {
773
+ fading: { type: 'boolean', default: true },
774
+ monitoring: { type: 'boolean', default: true },
775
+ },
776
+ },
777
+ },
778
+ required: ['task', 'scaffoldType'],
779
+ },
780
+ handler: scaffoldHandler,
781
+ };
782
+ // ============================================================================
783
+ // Tool 5: Cognitive Load
784
+ // ============================================================================
785
+ async function cognitiveLoadHandler(input, context) {
786
+ const logger = context?.logger ?? defaultLogger;
787
+ const startTime = performance.now();
788
+ try {
789
+ const validation = CognitiveLoadInputSchema.safeParse(input);
790
+ if (!validation.success) {
791
+ logger.error('Input validation failed', { error: validation.error.message });
792
+ return errorResult(`Invalid input: ${validation.error.message}`);
793
+ }
794
+ const { assessment, optimization, threshold } = validation.data;
795
+ logger.debug('Managing cognitive load', { optimization, threshold });
796
+ // Update current load if assessment provided
797
+ if (assessment) {
798
+ if (assessment.intrinsic !== undefined) {
799
+ currentCognitiveLoad.intrinsic = assessment.intrinsic;
800
+ }
801
+ if (assessment.extraneous !== undefined) {
802
+ currentCognitiveLoad.extraneous = assessment.extraneous;
803
+ }
804
+ if (assessment.germane !== undefined) {
805
+ currentCognitiveLoad.germane = assessment.germane;
806
+ }
807
+ }
808
+ const totalLoad = calculateTotalLoad(currentCognitiveLoad.intrinsic, currentCognitiveLoad.extraneous, currentCognitiveLoad.germane);
809
+ const overloaded = totalLoad > threshold;
810
+ // Generate recommendations based on optimization strategy
811
+ const recommendations = [];
812
+ switch (optimization) {
813
+ case 'reduce_extraneous':
814
+ if (currentCognitiveLoad.extraneous > 0.3) {
815
+ recommendations.push('Simplify presentation and remove unnecessary elements');
816
+ recommendations.push('Use consistent formatting and layout');
817
+ recommendations.push('Reduce visual clutter and distractions');
818
+ }
819
+ break;
820
+ case 'chunk_intrinsic':
821
+ if (currentCognitiveLoad.intrinsic > 0.5) {
822
+ recommendations.push('Break complex concepts into smaller chunks');
823
+ recommendations.push('Present information sequentially, not all at once');
824
+ recommendations.push('Build on prior knowledge incrementally');
825
+ }
826
+ break;
827
+ case 'maximize_germane':
828
+ if (currentCognitiveLoad.germane < 0.4) {
829
+ recommendations.push('Encourage active processing and elaboration');
830
+ recommendations.push('Connect new information to existing knowledge');
831
+ recommendations.push('Provide opportunities for practice and application');
832
+ }
833
+ break;
834
+ case 'balanced':
835
+ default:
836
+ if (overloaded) {
837
+ if (currentCognitiveLoad.extraneous > currentCognitiveLoad.intrinsic) {
838
+ recommendations.push('Reduce extraneous load first - simplify presentation');
839
+ }
840
+ else {
841
+ recommendations.push('Chunk intrinsic load - break down complexity');
842
+ }
843
+ }
844
+ if (currentCognitiveLoad.germane < 0.3) {
845
+ recommendations.push('Increase germane load - add meaningful learning activities');
846
+ }
847
+ break;
848
+ }
849
+ // Add general recommendations based on total load
850
+ if (overloaded) {
851
+ recommendations.push('Take a break to allow cognitive recovery');
852
+ recommendations.push('Consider offloading to external memory (notes, tools)');
853
+ }
854
+ else if (totalLoad < 0.3) {
855
+ recommendations.push('Cognitive resources available - can take on more complexity');
856
+ }
857
+ const interpretations = {
858
+ reduce_extraneous: 'Focusing on reducing presentation complexity',
859
+ chunk_intrinsic: 'Breaking down inherent task complexity',
860
+ maximize_germane: 'Maximizing productive learning load',
861
+ balanced: 'Balancing all cognitive load components',
862
+ };
863
+ const output = {
864
+ currentLoad: {
865
+ intrinsic: currentCognitiveLoad.intrinsic,
866
+ extraneous: currentCognitiveLoad.extraneous,
867
+ germane: currentCognitiveLoad.germane,
868
+ total: totalLoad,
869
+ },
870
+ overloaded,
871
+ recommendations,
872
+ details: {
873
+ optimization,
874
+ threshold,
875
+ interpretation: overloaded
876
+ ? `Cognitive overload detected (${(totalLoad * 100).toFixed(1)}% > ${(threshold * 100).toFixed(1)}%). ${interpretations[optimization]}`
877
+ : `Cognitive load is manageable (${(totalLoad * 100).toFixed(1)}%). ${interpretations[optimization]}`,
878
+ },
879
+ };
880
+ const duration = performance.now() - startTime;
881
+ logger.info('Cognitive load management completed', {
882
+ totalLoad: totalLoad.toFixed(2),
883
+ overloaded,
884
+ durationMs: duration.toFixed(2),
885
+ });
886
+ return successResult(output);
887
+ }
888
+ catch (error) {
889
+ logger.error('Cognitive load management failed', { error: error instanceof Error ? error.message : String(error) });
890
+ return errorResult(error instanceof Error ? error : new Error(String(error)));
891
+ }
892
+ }
893
+ export const cognitiveLoadTool = {
894
+ name: 'cognition/cognitive-load',
895
+ description: 'Monitor and balance cognitive load during reasoning. Manages intrinsic, extraneous, and germane load with optimization strategies.',
896
+ category: 'cognition',
897
+ version: '0.1.0',
898
+ tags: ['cognitive-load', 'clt', 'optimization', 'learning'],
899
+ cacheable: false,
900
+ inputSchema: {
901
+ type: 'object',
902
+ properties: {
903
+ assessment: {
904
+ type: 'object',
905
+ properties: {
906
+ intrinsic: { type: 'number', description: 'Task complexity (0-1)' },
907
+ extraneous: { type: 'number', description: 'Presentation complexity (0-1)' },
908
+ germane: { type: 'number', description: 'Learning investment (0-1)' },
909
+ },
910
+ },
911
+ optimization: {
912
+ type: 'string',
913
+ enum: ['reduce_extraneous', 'chunk_intrinsic', 'maximize_germane', 'balanced'],
914
+ default: 'balanced',
915
+ },
916
+ threshold: { type: 'number', default: 0.8 },
917
+ },
918
+ },
919
+ handler: cognitiveLoadHandler,
920
+ };
921
+ // ============================================================================
922
+ // Export All Tools
923
+ // ============================================================================
924
+ export const cognitiveKernelTools = [
925
+ workingMemoryTool,
926
+ attentionControlTool,
927
+ metaMonitorTool,
928
+ scaffoldTool,
929
+ cognitiveLoadTool,
930
+ ];
931
+ export const toolHandlers = new Map([
932
+ ['cognition/working-memory', workingMemoryTool.handler],
933
+ ['cognition/attention-control', attentionControlTool.handler],
934
+ ['cognition/meta-monitor', metaMonitorTool.handler],
935
+ ['cognition/scaffold', scaffoldTool.handler],
936
+ ['cognition/cognitive-load', cognitiveLoadTool.handler],
937
+ ]);
938
+ export function getTool(name) {
939
+ return cognitiveKernelTools.find(t => t.name === name);
940
+ }
941
+ export function getToolNames() {
942
+ return cognitiveKernelTools.map(t => t.name);
943
+ }
944
+ export default cognitiveKernelTools;
945
+ //# sourceMappingURL=mcp-tools.js.map