claude-flow 2.7.0-alpha.1 → 2.7.0-alpha.10

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 (89) hide show
  1. package/README.md +2 -32
  2. package/bin/claude-flow +8 -8
  3. package/dist/src/cli/help-formatter.js.map +1 -1
  4. package/dist/src/cli/simple-cli.js +172 -182
  5. package/dist/src/cli/simple-cli.js.map +1 -1
  6. package/dist/src/cli/simple-commands/config.js +257 -115
  7. package/dist/src/cli/simple-commands/config.js.map +1 -1
  8. package/dist/src/cli/simple-commands/init/index.js +45 -0
  9. package/dist/src/cli/simple-commands/init/index.js.map +1 -1
  10. package/dist/src/cli/simple-commands/memory.js +64 -19
  11. package/dist/src/cli/simple-commands/memory.js.map +1 -1
  12. package/dist/src/cli/simple-commands/performance-metrics.js +231 -1
  13. package/dist/src/cli/simple-commands/performance-metrics.js.map +1 -1
  14. package/dist/src/cli/validation-helper.js.map +1 -1
  15. package/dist/src/core/version.js +1 -1
  16. package/dist/src/reasoningbank/reasoningbank-adapter.js +260 -121
  17. package/dist/src/reasoningbank/reasoningbank-adapter.js.map +1 -1
  18. package/dist/src/utils/key-redactor.js.map +1 -1
  19. package/dist/src/utils/metrics-reader.js +29 -41
  20. package/dist/src/utils/metrics-reader.js.map +1 -1
  21. package/docker-test/.claude-flow/metrics/agent-metrics.json +1 -0
  22. package/docker-test/.claude-flow/metrics/performance.json +87 -0
  23. package/docker-test/.claude-flow/metrics/task-metrics.json +10 -0
  24. package/docker-test/Dockerfile.reasoningbank-test +21 -0
  25. package/docker-test/reasoningbank-validation.mjs +201 -0
  26. package/docs/.claude-flow/metrics/agent-metrics.json +1 -0
  27. package/docs/.claude-flow/metrics/performance.json +9 -0
  28. package/docs/.claude-flow/metrics/task-metrics.json +10 -0
  29. package/docs/CLI-MEMORY-COMMANDS-WORKING.md +150 -0
  30. package/docs/INDEX.md +36 -5
  31. package/docs/PERFORMANCE-JSON-IMPROVEMENTS.md +277 -0
  32. package/docs/PERFORMANCE-METRICS-GUIDE.md +259 -0
  33. package/docs/RELEASE-NOTES-v2.7.0-alpha.10.md +309 -0
  34. package/docs/RELEASE-NOTES-v2.7.0-alpha.9.md +208 -0
  35. package/docs/integrations/README.md +61 -0
  36. package/docs/{AGENTIC_FLOW_SECURITY_TEST_REPORT.md → integrations/agentic-flow/AGENTIC_FLOW_SECURITY_TEST_REPORT.md} +7 -7
  37. package/docs/integrations/reasoningbank/MIGRATION-v1.5.13.md +189 -0
  38. package/docs/integrations/reasoningbank/REASONINGBANK-STATUS.md +219 -0
  39. package/docs/reports/README.md +49 -0
  40. package/docs/reports/REASONINGBANK_STATUS_UPDATE_v2_7_0_alpha_7.md +366 -0
  41. package/docs/reports/validation/DOCKER-VALIDATION-REPORT-v2.7.0-alpha.7.md +361 -0
  42. package/docs/reports/validation/DOCKER_SQL_FALLBACK_VALIDATION.md +398 -0
  43. package/docs/{MEMORY_REDACTION_TEST_REPORT.md → reports/validation/MEMORY_REDACTION_TEST_REPORT.md} +7 -7
  44. package/docs/reports/validation/PROCESS-EXIT-FIX-v2.7.0-alpha.9.md +154 -0
  45. package/docs/reports/validation/REASONINGBANK-v1.5.13-VALIDATION.md +235 -0
  46. package/docs/reports/validation/SQL_FALLBACK_VALIDATION_REPORT.md +405 -0
  47. package/docs/reports/validation/VALIDATION-SUMMARY.md +192 -0
  48. package/docs/setup/MCP-SETUP-GUIDE.md +154 -0
  49. package/docs/technical/README.md +36 -0
  50. package/docs/technical/fixes/WASM-ESM-FIX-SUMMARY.md +114 -0
  51. package/package.json +6 -6
  52. package/src/cli/simple-commands/init/index.js +70 -0
  53. package/src/cli/simple-commands/memory.js +89 -21
  54. package/src/cli/simple-commands/performance-metrics.js +268 -2
  55. package/src/reasoningbank/reasoningbank-adapter.js +360 -148
  56. /package/docs/{AGENT-BOOSTER-INTEGRATION.md → integrations/agent-booster/AGENT-BOOSTER-INTEGRATION.md} +0 -0
  57. /package/docs/{AGENTIC-FLOW-INTEGRATION-GUIDE.md → integrations/agentic-flow/AGENTIC-FLOW-INTEGRATION-GUIDE.md} +0 -0
  58. /package/docs/{AGENTIC_FLOW_EXECUTION_FIX_REPORT.md → integrations/agentic-flow/AGENTIC_FLOW_EXECUTION_FIX_REPORT.md} +0 -0
  59. /package/docs/{AGENTIC_FLOW_INTEGRATION_STATUS.md → integrations/agentic-flow/AGENTIC_FLOW_INTEGRATION_STATUS.md} +0 -0
  60. /package/docs/{AGENTIC_FLOW_MVP_COMPLETE.md → integrations/agentic-flow/AGENTIC_FLOW_MVP_COMPLETE.md} +0 -0
  61. /package/docs/{epic-sdk-integration.md → integrations/epic-sdk/epic-sdk-integration.md} +0 -0
  62. /package/docs/{REASONING-AGENTS.md → integrations/reasoningbank/REASONING-AGENTS.md} +0 -0
  63. /package/docs/{REASONINGBANK-AGENT-CREATION-GUIDE.md → integrations/reasoningbank/REASONINGBANK-AGENT-CREATION-GUIDE.md} +0 -0
  64. /package/docs/{REASONINGBANK-ANALYSIS-COMPLETE.md → integrations/reasoningbank/REASONINGBANK-ANALYSIS-COMPLETE.md} +0 -0
  65. /package/docs/{REASONINGBANK-BENCHMARK-RESULTS.md → integrations/reasoningbank/REASONINGBANK-BENCHMARK-RESULTS.md} +0 -0
  66. /package/docs/{REASONINGBANK-BENCHMARK.md → integrations/reasoningbank/REASONINGBANK-BENCHMARK.md} +0 -0
  67. /package/docs/{REASONINGBANK-CLI-INTEGRATION.md → integrations/reasoningbank/REASONINGBANK-CLI-INTEGRATION.md} +0 -0
  68. /package/docs/{REASONINGBANK-CORE-INTEGRATION.md → integrations/reasoningbank/REASONINGBANK-CORE-INTEGRATION.md} +0 -0
  69. /package/docs/{REASONINGBANK-COST-OPTIMIZATION.md → integrations/reasoningbank/REASONINGBANK-COST-OPTIMIZATION.md} +0 -0
  70. /package/docs/{REASONINGBANK-DEMO.md → integrations/reasoningbank/REASONINGBANK-DEMO.md} +0 -0
  71. /package/docs/{REASONINGBANK-INTEGRATION-COMPLETE.md → integrations/reasoningbank/REASONINGBANK-INTEGRATION-COMPLETE.md} +0 -0
  72. /package/docs/{REASONINGBANK-INTEGRATION-STATUS.md → integrations/reasoningbank/REASONINGBANK-INTEGRATION-STATUS.md} +0 -0
  73. /package/docs/{REASONINGBANK-VALIDATION.md → integrations/reasoningbank/REASONINGBANK-VALIDATION.md} +0 -0
  74. /package/docs/{REASONINGBANK_ARCHITECTURE.md → integrations/reasoningbank/REASONINGBANK_ARCHITECTURE.md} +0 -0
  75. /package/docs/{REASONINGBANK_INTEGRATION_COMPLETE.md → integrations/reasoningbank/REASONINGBANK_INTEGRATION_COMPLETE.md} +0 -0
  76. /package/docs/{REASONINGBANK_INTEGRATION_PLAN.md → integrations/reasoningbank/REASONINGBANK_INTEGRATION_PLAN.md} +0 -0
  77. /package/docs/{DEEP_REVIEW_COMPREHENSIVE_REPORT.md → reports/analysis/DEEP_REVIEW_COMPREHENSIVE_REPORT.md} +0 -0
  78. /package/docs/{REGRESSION-ANALYSIS-REPORT.md → reports/analysis/REGRESSION-ANALYSIS-REPORT.md} +0 -0
  79. /package/docs/{COMMIT_SUMMARY.md → reports/releases/COMMIT_SUMMARY.md} +0 -0
  80. /package/docs/{INTEGRATION_COMPLETE.md → reports/releases/INTEGRATION_COMPLETE.md} +0 -0
  81. /package/docs/{PRE_RELEASE_FIXES_REPORT.md → reports/releases/PRE_RELEASE_FIXES_REPORT.md} +0 -0
  82. /package/docs/{RELEASE_v2.6.0-alpha.2.md → reports/releases/RELEASE_v2.6.0-alpha.2.md} +0 -0
  83. /package/docs/{COMMAND-VERIFICATION-REPORT.md → reports/validation/COMMAND-VERIFICATION-REPORT.md} +0 -0
  84. /package/docs/{DOCKER-VALIDATION-REPORT.md → reports/validation/DOCKER-VALIDATION-REPORT.md} +0 -0
  85. /package/docs/{FINAL_PRE_PUBLISH_VALIDATION.md → reports/validation/FINAL_PRE_PUBLISH_VALIDATION.md} +0 -0
  86. /package/docs/{FINAL_VALIDATION_REPORT.md → reports/validation/FINAL_VALIDATION_REPORT.md} +0 -0
  87. /package/docs/{ENV-SETUP-GUIDE.md → setup/ENV-SETUP-GUIDE.md} +0 -0
  88. /package/docs/{HOOKS-V2-MODIFICATION.md → technical/fixes/HOOKS-V2-MODIFICATION.md} +0 -0
  89. /package/docs/{PERFORMANCE-SYSTEMS-STATUS.md → technical/performance/PERFORMANCE-SYSTEMS-STATUS.md} +0 -0
@@ -402,8 +402,15 @@ async function detectMemoryMode(flags, subArgs) {
402
402
  return initialized ? 'reasoningbank' : 'basic';
403
403
  }
404
404
 
405
- // Default: basic mode (backward compatible)
406
- return 'basic';
405
+ // Explicit basic mode flag
406
+ if (flags?.basic || subArgs.includes('--basic')) {
407
+ return 'basic';
408
+ }
409
+
410
+ // Default: AUTO MODE (smart selection with JSON fallback)
411
+ // Automatically use ReasoningBank if initialized, otherwise fall back to basic mode
412
+ const initialized = await isReasoningBankInitialized();
413
+ return initialized ? 'reasoningbank' : 'basic';
407
414
  }
408
415
 
409
416
  // NEW: Check if ReasoningBank is initialized
@@ -423,17 +430,60 @@ async function handleReasoningBankCommand(command, subArgs, flags) {
423
430
  const initialized = await isReasoningBankInitialized();
424
431
 
425
432
  // Lazy load the adapter (ES modules)
426
- const { initializeReasoningBank, storeMemory, queryMemories, listMemories, getStatus } = await import('../../reasoningbank/reasoningbank-adapter.js');
433
+ const { initializeReasoningBank, storeMemory, queryMemories, listMemories, getStatus, checkReasoningBankTables, migrateReasoningBank, cleanup } = await import('../../reasoningbank/reasoningbank-adapter.js');
427
434
 
428
435
  // Special handling for 'init' command
429
436
  if (command === 'init') {
437
+ const dbPath = '.swarm/memory.db';
438
+
430
439
  if (initialized) {
431
- printWarning('⚠️ ReasoningBank already initialized');
432
- console.log('Database: .swarm/memory.db');
433
- console.log('\nTo reinitialize, delete .swarm/memory.db first');
440
+ // Database exists - check if migration is needed
441
+ printInfo('🔍 Checking existing database for ReasoningBank schema...\n');
442
+
443
+ try {
444
+ // Set the database path for ReasoningBank
445
+ process.env.CLAUDE_FLOW_DB_PATH = dbPath;
446
+
447
+ const tableCheck = await checkReasoningBankTables();
448
+
449
+ if (tableCheck.exists) {
450
+ printSuccess('✅ ReasoningBank already complete');
451
+ console.log('Database: .swarm/memory.db');
452
+ console.log('All ReasoningBank tables present\n');
453
+ console.log('Use --reasoningbank flag with memory commands to enable AI features');
454
+ return;
455
+ }
456
+
457
+ // Missing tables found - run migration
458
+ console.log(`🔄 Migrating database: ${tableCheck.missingTables.length} tables missing`);
459
+ console.log(` Missing: ${tableCheck.missingTables.join(', ')}\n`);
460
+
461
+ const migrationResult = await migrateReasoningBank();
462
+
463
+ if (migrationResult.success) {
464
+ printSuccess(`✓ Migration complete: added ${migrationResult.addedTables?.length || 0} tables`);
465
+ console.log('\nNext steps:');
466
+ console.log(' 1. Store memories: memory store key "value" --reasoningbank');
467
+ console.log(' 2. Query memories: memory query "search" --reasoningbank');
468
+ console.log(' 3. Check status: memory status --reasoningbank');
469
+ } else {
470
+ printError(`❌ Migration failed: ${migrationResult.message}`);
471
+ console.log('Try running: init --force to reinitialize');
472
+ }
473
+ } catch (error) {
474
+ printError('❌ Migration check failed');
475
+ console.error(error.message);
476
+ console.log('\nTry running: init --force to reinitialize');
477
+ } finally {
478
+ // Cleanup after migration check
479
+ cleanup();
480
+ // Force exit to prevent hanging from embedding cache timers
481
+ setTimeout(() => process.exit(0), 100);
482
+ }
434
483
  return;
435
484
  }
436
485
 
486
+ // Fresh initialization
437
487
  printInfo('🧠 Initializing ReasoningBank...');
438
488
  console.log('This will create: .swarm/memory.db\n');
439
489
 
@@ -447,6 +497,11 @@ async function handleReasoningBankCommand(command, subArgs, flags) {
447
497
  } catch (error) {
448
498
  printError('❌ Failed to initialize ReasoningBank');
449
499
  console.error(error.message);
500
+ } finally {
501
+ // Cleanup after init
502
+ cleanup();
503
+ // Force exit to prevent hanging from embedding cache timers
504
+ setTimeout(() => process.exit(0), 100);
450
505
  }
451
506
  return;
452
507
  }
@@ -496,6 +551,16 @@ async function handleReasoningBankCommand(command, subArgs, flags) {
496
551
  } catch (error) {
497
552
  printError(`❌ ReasoningBank command failed`);
498
553
  console.error(error.message);
554
+ } finally {
555
+ // Always cleanup database connection
556
+ cleanup();
557
+
558
+ // Force process exit after cleanup (embedding cache timers prevent natural exit)
559
+ // This is necessary because agentic-flow's embedding cache uses setTimeout
560
+ // which keeps the event loop alive
561
+ setTimeout(() => {
562
+ process.exit(0);
563
+ }, 100);
499
564
  }
500
565
  }
501
566
 
@@ -713,15 +778,16 @@ async function showCurrentMode() {
713
778
  const rbInitialized = await isReasoningBankInitialized();
714
779
 
715
780
  printInfo('📊 Current Memory Configuration:\n');
716
- console.log('Default Mode: Basic (backward compatible)');
781
+ console.log('Default Mode: AUTO (smart selection with JSON fallback)');
717
782
  console.log('Available Modes:');
718
- console.log(' • Basic Mode: Always available');
719
- console.log(` • ReasoningBank Mode: ${rbInitialized ? 'Initialized ✅' : 'Not initialized ⚠️'}`);
720
-
721
- console.log('\n💡 To use a specific mode:');
722
- console.log(' --reasoningbank or --rb → Use ReasoningBank');
723
- console.log(' --auto Auto-detect best mode');
724
- console.log(' (no flag) Use Basic mode');
783
+ console.log(' • Basic Mode: Always available (JSON storage)');
784
+ console.log(` • ReasoningBank Mode: ${rbInitialized ? 'Initialized ✅ (will be used by default)' : 'Not initialized ⚠️ (JSON fallback active)'}`);
785
+
786
+ console.log('\n💡 Mode Behavior:');
787
+ console.log(' (no flag) AUTO: Use ReasoningBank if initialized, else JSON');
788
+ console.log(' --reasoningbank or --rb Force ReasoningBank mode');
789
+ console.log(' --basic Force JSON mode');
790
+ console.log(' --auto → Same as default (explicit)');
725
791
  }
726
792
 
727
793
  // NEW: Migrate memory between modes
@@ -788,10 +854,11 @@ function showMemoryHelp() {
788
854
  console.log(' --redact 🔒 Enable API key redaction (security feature)');
789
855
  console.log(' --secure Alias for --redact');
790
856
  console.log();
791
- console.log('🎯 Mode Selection (NEW):');
792
- console.log(' --reasoningbank, --rb Use ReasoningBank mode (AI-powered)');
793
- console.log(' --auto Auto-detect best available mode');
794
- console.log(' (no flag) Use Basic mode (default, backward compatible)');
857
+ console.log('🎯 Mode Selection:');
858
+ console.log(' (no flag) AUTO MODE (default) - Uses ReasoningBank if initialized, else JSON fallback');
859
+ console.log(' --reasoningbank, --rb Force ReasoningBank mode (AI-powered)');
860
+ console.log(' --basic Force Basic mode (JSON storage)');
861
+ console.log(' --auto Explicit auto-detect (same as default)');
795
862
  console.log();
796
863
  console.log('🔒 Security Features (v2.6.0):');
797
864
  console.log(' API Key Protection: Automatically detects and redacts sensitive data');
@@ -819,8 +886,9 @@ function showMemoryHelp() {
819
886
  console.log(' memory mode # Show current configuration');
820
887
  console.log();
821
888
  console.log('💡 Tips:');
822
- console.log(' • Use Basic mode for simple key-value storage (fast, always available)');
823
- console.log(' • Use ReasoningBank for AI-powered semantic search (learns from patterns)');
824
- console.log(' • Use --auto to let claude-flow choose the best mode for you');
889
+ console.log(' • AUTO MODE (default): Automatically uses best available storage');
890
+ console.log(' • ReasoningBank: AI-powered semantic search (learns from patterns)');
891
+ console.log(' • JSON fallback: Always available, fast, simple key-value storage');
892
+ console.log(' • Initialize ReasoningBank once: "memory init --reasoningbank"');
825
893
  console.log(' • Always use --redact when storing API keys or secrets!');
826
894
  }
@@ -21,13 +21,78 @@ let metricsCache = {
21
21
  agents: {},
22
22
  system: [],
23
23
  performance: {
24
+ // Session information
24
25
  startTime: Date.now(),
26
+ sessionId: `session-${Date.now()}`,
27
+ lastActivity: Date.now(),
28
+ sessionDuration: 0,
29
+
30
+ // General task metrics
25
31
  totalTasks: 0,
26
32
  successfulTasks: 0,
27
33
  failedTasks: 0,
28
34
  totalAgents: 0,
29
35
  activeAgents: 0,
30
- neuralEvents: 0
36
+ neuralEvents: 0,
37
+
38
+ // Memory mode tracking
39
+ memoryMode: {
40
+ reasoningbankOperations: 0,
41
+ basicOperations: 0,
42
+ autoModeSelections: 0,
43
+ modeOverrides: 0,
44
+ currentMode: 'auto'
45
+ },
46
+
47
+ // Operation type breakdown
48
+ operations: {
49
+ store: { count: 0, totalDuration: 0, errors: 0 },
50
+ retrieve: { count: 0, totalDuration: 0, errors: 0 },
51
+ query: { count: 0, totalDuration: 0, errors: 0 },
52
+ list: { count: 0, totalDuration: 0, errors: 0 },
53
+ delete: { count: 0, totalDuration: 0, errors: 0 },
54
+ search: { count: 0, totalDuration: 0, errors: 0 },
55
+ init: { count: 0, totalDuration: 0, errors: 0 }
56
+ },
57
+
58
+ // Performance statistics
59
+ performance: {
60
+ avgOperationDuration: 0,
61
+ minOperationDuration: null,
62
+ maxOperationDuration: null,
63
+ slowOperations: 0, // Count of operations > 5s
64
+ fastOperations: 0, // Count of operations < 100ms
65
+ totalOperationTime: 0
66
+ },
67
+
68
+ // Memory storage statistics
69
+ storage: {
70
+ totalEntries: 0,
71
+ reasoningbankEntries: 0,
72
+ basicEntries: 0,
73
+ databaseSize: 0,
74
+ lastBackup: null,
75
+ growthRate: 0
76
+ },
77
+
78
+ // Error tracking
79
+ errors: {
80
+ total: 0,
81
+ byType: {},
82
+ byOperation: {},
83
+ recent: []
84
+ },
85
+
86
+ // ReasoningBank specific metrics
87
+ reasoningbank: {
88
+ semanticSearches: 0,
89
+ sqlFallbacks: 0,
90
+ embeddingGenerated: 0,
91
+ consolidations: 0,
92
+ avgQueryTime: 0,
93
+ cacheHits: 0,
94
+ cacheMisses: 0
95
+ }
31
96
  }
32
97
  };
33
98
 
@@ -162,10 +227,211 @@ export async function trackAgentActivity(agentId, agentType, action, duration, s
162
227
  // Track neural events
163
228
  export async function trackNeuralEvent(eventType, metadata = {}) {
164
229
  metricsCache.performance.neuralEvents++;
165
-
230
+
166
231
  await saveMetricsToDisk();
167
232
  }
168
233
 
234
+ // Track memory operations
235
+ export async function trackMemoryOperation(operationType, mode, duration, success = true, errorType = null) {
236
+ // Update session activity
237
+ metricsCache.performance.lastActivity = Date.now();
238
+ metricsCache.performance.sessionDuration = Date.now() - metricsCache.performance.startTime;
239
+
240
+ // Track mode usage
241
+ if (mode === 'reasoningbank') {
242
+ metricsCache.performance.memoryMode.reasoningbankOperations++;
243
+ } else if (mode === 'basic') {
244
+ metricsCache.performance.memoryMode.basicOperations++;
245
+ }
246
+
247
+ // Track operation type
248
+ if (metricsCache.performance.operations[operationType]) {
249
+ const op = metricsCache.performance.operations[operationType];
250
+ op.count++;
251
+ op.totalDuration += duration;
252
+
253
+ if (!success) {
254
+ op.errors++;
255
+ }
256
+ }
257
+
258
+ // Update performance statistics
259
+ const perf = metricsCache.performance.performance;
260
+ perf.totalOperationTime += duration;
261
+
262
+ const totalOps = Object.values(metricsCache.performance.operations)
263
+ .reduce((sum, op) => sum + op.count, 0);
264
+
265
+ if (totalOps > 0) {
266
+ perf.avgOperationDuration = perf.totalOperationTime / totalOps;
267
+ }
268
+
269
+ if (perf.minOperationDuration === null || duration < perf.minOperationDuration) {
270
+ perf.minOperationDuration = duration;
271
+ }
272
+
273
+ if (perf.maxOperationDuration === null || duration > perf.maxOperationDuration) {
274
+ perf.maxOperationDuration = duration;
275
+ }
276
+
277
+ if (duration > 5000) {
278
+ perf.slowOperations++;
279
+ } else if (duration < 100) {
280
+ perf.fastOperations++;
281
+ }
282
+
283
+ // Track errors
284
+ if (!success && errorType) {
285
+ metricsCache.performance.errors.total++;
286
+
287
+ // Track by type
288
+ if (!metricsCache.performance.errors.byType[errorType]) {
289
+ metricsCache.performance.errors.byType[errorType] = 0;
290
+ }
291
+ metricsCache.performance.errors.byType[errorType]++;
292
+
293
+ // Track by operation
294
+ if (!metricsCache.performance.errors.byOperation[operationType]) {
295
+ metricsCache.performance.errors.byOperation[operationType] = 0;
296
+ }
297
+ metricsCache.performance.errors.byOperation[operationType]++;
298
+
299
+ // Add to recent errors (keep last 20)
300
+ metricsCache.performance.errors.recent.push({
301
+ operation: operationType,
302
+ type: errorType,
303
+ timestamp: Date.now(),
304
+ mode
305
+ });
306
+
307
+ if (metricsCache.performance.errors.recent.length > 20) {
308
+ metricsCache.performance.errors.recent = metricsCache.performance.errors.recent.slice(-20);
309
+ }
310
+ }
311
+
312
+ await saveMetricsToDisk();
313
+ }
314
+
315
+ // Track mode selection (auto, override)
316
+ export async function trackModeSelection(selectedMode, wasAutomatic = true) {
317
+ metricsCache.performance.memoryMode.currentMode = selectedMode;
318
+
319
+ if (wasAutomatic) {
320
+ metricsCache.performance.memoryMode.autoModeSelections++;
321
+ } else {
322
+ metricsCache.performance.memoryMode.modeOverrides++;
323
+ }
324
+
325
+ await saveMetricsToDisk();
326
+ }
327
+
328
+ // Track ReasoningBank specific operations
329
+ export async function trackReasoningBankOperation(operationType, duration, metadata = {}) {
330
+ const rb = metricsCache.performance.reasoningbank;
331
+
332
+ switch (operationType) {
333
+ case 'semantic_search':
334
+ rb.semanticSearches++;
335
+ break;
336
+ case 'sql_fallback':
337
+ rb.sqlFallbacks++;
338
+ break;
339
+ case 'embedding_generated':
340
+ rb.embeddingGenerated++;
341
+ break;
342
+ case 'consolidation':
343
+ rb.consolidations++;
344
+ break;
345
+ case 'cache_hit':
346
+ rb.cacheHits++;
347
+ break;
348
+ case 'cache_miss':
349
+ rb.cacheMisses++;
350
+ break;
351
+ }
352
+
353
+ // Update average query time
354
+ const totalQueries = rb.semanticSearches + rb.sqlFallbacks;
355
+ if (totalQueries > 0) {
356
+ rb.avgQueryTime = ((rb.avgQueryTime * (totalQueries - 1)) + duration) / totalQueries;
357
+ }
358
+
359
+ await saveMetricsToDisk();
360
+ }
361
+
362
+ // Update storage statistics
363
+ export async function updateStorageStats(totalEntries, reasoningbankEntries, basicEntries, databaseSize = 0) {
364
+ const storage = metricsCache.performance.storage;
365
+
366
+ const previousTotal = storage.totalEntries;
367
+ storage.totalEntries = totalEntries;
368
+ storage.reasoningbankEntries = reasoningbankEntries;
369
+ storage.basicEntries = basicEntries;
370
+ storage.databaseSize = databaseSize;
371
+
372
+ // Calculate growth rate (entries per hour)
373
+ if (previousTotal > 0) {
374
+ const sessionHours = metricsCache.performance.sessionDuration / (1000 * 60 * 60);
375
+ if (sessionHours > 0) {
376
+ storage.growthRate = (totalEntries - previousTotal) / sessionHours;
377
+ }
378
+ }
379
+
380
+ await saveMetricsToDisk();
381
+ }
382
+
383
+ // Get memory performance summary
384
+ export async function getMemoryPerformanceSummary() {
385
+ const perf = metricsCache.performance;
386
+ const totalOps = Object.values(perf.operations).reduce((sum, op) => sum + op.count, 0);
387
+ const totalErrors = Object.values(perf.operations).reduce((sum, op) => sum + op.errors, 0);
388
+
389
+ return {
390
+ session: {
391
+ sessionId: perf.sessionId,
392
+ duration: perf.sessionDuration,
393
+ startTime: new Date(perf.startTime).toISOString(),
394
+ lastActivity: new Date(perf.lastActivity).toISOString()
395
+ },
396
+ mode: {
397
+ current: perf.memoryMode.currentMode,
398
+ reasoningbankUsage: perf.memoryMode.reasoningbankOperations,
399
+ basicUsage: perf.memoryMode.basicOperations,
400
+ autoSelections: perf.memoryMode.autoModeSelections,
401
+ manualOverrides: perf.memoryMode.modeOverrides
402
+ },
403
+ operations: {
404
+ total: totalOps,
405
+ breakdown: perf.operations,
406
+ errors: totalErrors,
407
+ errorRate: totalOps > 0 ? (totalErrors / totalOps) * 100 : 0
408
+ },
409
+ performance: {
410
+ avgDuration: perf.performance.avgOperationDuration,
411
+ minDuration: perf.performance.minOperationDuration,
412
+ maxDuration: perf.performance.maxOperationDuration,
413
+ slowOps: perf.performance.slowOperations,
414
+ fastOps: perf.performance.fastOperations
415
+ },
416
+ storage: perf.storage,
417
+ reasoningbank: {
418
+ ...perf.reasoningbank,
419
+ fallbackRate: perf.reasoningbank.semanticSearches > 0
420
+ ? (perf.reasoningbank.sqlFallbacks / perf.reasoningbank.semanticSearches) * 100
421
+ : 0,
422
+ cacheHitRate: (perf.reasoningbank.cacheHits + perf.reasoningbank.cacheMisses) > 0
423
+ ? (perf.reasoningbank.cacheHits / (perf.reasoningbank.cacheHits + perf.reasoningbank.cacheMisses)) * 100
424
+ : 0
425
+ },
426
+ errors: {
427
+ total: perf.errors.total,
428
+ byType: perf.errors.byType,
429
+ byOperation: perf.errors.byOperation,
430
+ recent: perf.errors.recent.slice(-5)
431
+ }
432
+ };
433
+ }
434
+
169
435
  // Get performance report data
170
436
  export async function getPerformanceReport(timeframe = '24h') {
171
437
  const now = Date.now();