claude-flow 2.7.0-alpha.7 ā 2.7.0-alpha.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.
- package/bin/claude-flow +1 -1
- package/dist/src/cli/help-formatter.js +5 -0
- package/dist/src/cli/simple-commands/memory.js +22 -15
- package/dist/src/cli/simple-commands/memory.js.map +1 -1
- package/dist/src/cli/simple-commands/performance-metrics.js +231 -1
- package/dist/src/cli/simple-commands/performance-metrics.js.map +1 -1
- package/dist/src/cli/validation-helper.js.map +1 -1
- package/dist/src/core/version.js.map +1 -1
- package/dist/src/memory/swarm-memory.js +340 -421
- package/dist/src/memory/swarm-memory.js.map +1 -1
- package/dist/src/utils/key-redactor.js.map +1 -1
- package/dist/src/utils/metrics-reader.js +37 -39
- package/dist/src/utils/metrics-reader.js.map +1 -1
- package/docs/.claude-flow/metrics/performance.json +1 -1
- package/docs/.claude-flow/metrics/task-metrics.json +3 -3
- package/docs/PERFORMANCE-JSON-IMPROVEMENTS.md +277 -0
- package/docs/PERFORMANCE-METRICS-GUIDE.md +259 -0
- package/docs/integrations/agentic-flow/AGENTIC_FLOW_SECURITY_TEST_REPORT.md +7 -7
- package/docs/integrations/reasoningbank/MIGRATION-v1.5.13.md +189 -0
- package/docs/reports/REASONINGBANK_STATUS_UPDATE_v2_7_0_alpha_7.md +366 -0
- package/docs/reports/validation/DOCKER_SQL_FALLBACK_VALIDATION.md +398 -0
- package/docs/reports/validation/MEMORY_REDACTION_TEST_REPORT.md +7 -7
- package/docs/reports/validation/SQL_FALLBACK_VALIDATION_REPORT.md +405 -0
- package/docs/setup/MCP-SETUP-GUIDE.md +154 -0
- package/package.json +5 -6
- package/src/cli/simple-commands/memory.js +27 -17
- package/src/cli/simple-commands/performance-metrics.js +268 -2
- package/src/reasoningbank/reasoningbank-adapter.js +183 -132
package/bin/claude-flow
CHANGED
|
@@ -315,7 +315,11 @@ async function detectMemoryMode(flags, subArgs) {
|
|
|
315
315
|
const initialized = await isReasoningBankInitialized();
|
|
316
316
|
return initialized ? 'reasoningbank' : 'basic';
|
|
317
317
|
}
|
|
318
|
-
|
|
318
|
+
if (flags?.basic || subArgs.includes('--basic')) {
|
|
319
|
+
return 'basic';
|
|
320
|
+
}
|
|
321
|
+
const initialized = await isReasoningBankInitialized();
|
|
322
|
+
return initialized ? 'reasoningbank' : 'basic';
|
|
319
323
|
}
|
|
320
324
|
async function isReasoningBankInitialized() {
|
|
321
325
|
try {
|
|
@@ -590,14 +594,15 @@ async function checkBasicMode() {
|
|
|
590
594
|
async function showCurrentMode() {
|
|
591
595
|
const rbInitialized = await isReasoningBankInitialized();
|
|
592
596
|
printInfo('š Current Memory Configuration:\n');
|
|
593
|
-
console.log('Default Mode:
|
|
597
|
+
console.log('Default Mode: AUTO (smart selection with JSON fallback)');
|
|
594
598
|
console.log('Available Modes:');
|
|
595
|
-
console.log(' ⢠Basic Mode: Always available');
|
|
596
|
-
console.log(` ⢠ReasoningBank Mode: ${rbInitialized ? 'Initialized ā
' : 'Not initialized ā ļø'}`);
|
|
597
|
-
console.log('\nš”
|
|
598
|
-
console.log('
|
|
599
|
-
console.log(' --
|
|
600
|
-
console.log('
|
|
599
|
+
console.log(' ⢠Basic Mode: Always available (JSON storage)');
|
|
600
|
+
console.log(` ⢠ReasoningBank Mode: ${rbInitialized ? 'Initialized ā
(will be used by default)' : 'Not initialized ā ļø (JSON fallback active)'}`);
|
|
601
|
+
console.log('\nš” Mode Behavior:');
|
|
602
|
+
console.log(' (no flag) ā AUTO: Use ReasoningBank if initialized, else JSON');
|
|
603
|
+
console.log(' --reasoningbank or --rb ā Force ReasoningBank mode');
|
|
604
|
+
console.log(' --basic ā Force JSON mode');
|
|
605
|
+
console.log(' --auto ā Same as default (explicit)');
|
|
601
606
|
}
|
|
602
607
|
async function migrateMemory(subArgs, flags) {
|
|
603
608
|
const targetMode = flags?.to || getArgValue(subArgs, '--to');
|
|
@@ -656,10 +661,11 @@ function showMemoryHelp() {
|
|
|
656
661
|
console.log(' --redact š Enable API key redaction (security feature)');
|
|
657
662
|
console.log(' --secure Alias for --redact');
|
|
658
663
|
console.log();
|
|
659
|
-
console.log('šÆ Mode Selection
|
|
660
|
-
console.log('
|
|
661
|
-
console.log(' --
|
|
662
|
-
console.log('
|
|
664
|
+
console.log('šÆ Mode Selection:');
|
|
665
|
+
console.log(' (no flag) AUTO MODE (default) - Uses ReasoningBank if initialized, else JSON fallback');
|
|
666
|
+
console.log(' --reasoningbank, --rb Force ReasoningBank mode (AI-powered)');
|
|
667
|
+
console.log(' --basic Force Basic mode (JSON storage)');
|
|
668
|
+
console.log(' --auto Explicit auto-detect (same as default)');
|
|
663
669
|
console.log();
|
|
664
670
|
console.log('š Security Features (v2.6.0):');
|
|
665
671
|
console.log(' API Key Protection: Automatically detects and redacts sensitive data');
|
|
@@ -687,9 +693,10 @@ function showMemoryHelp() {
|
|
|
687
693
|
console.log(' memory mode # Show current configuration');
|
|
688
694
|
console.log();
|
|
689
695
|
console.log('š” Tips:');
|
|
690
|
-
console.log(' ā¢
|
|
691
|
-
console.log(' ā¢
|
|
692
|
-
console.log(' ā¢
|
|
696
|
+
console.log(' ⢠AUTO MODE (default): Automatically uses best available storage');
|
|
697
|
+
console.log(' ⢠ReasoningBank: AI-powered semantic search (learns from patterns)');
|
|
698
|
+
console.log(' ⢠JSON fallback: Always available, fast, simple key-value storage');
|
|
699
|
+
console.log(' ⢠Initialize ReasoningBank once: "memory init --reasoningbank"');
|
|
693
700
|
console.log(' ⢠Always use --redact when storing API keys or secrets!');
|
|
694
701
|
}
|
|
695
702
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/cli/simple-commands/memory.js"],"sourcesContent":["// memory.js - Memory management commands\nimport { printSuccess, printError, printWarning, printInfo } from '../utils.js';\nimport { promises as fs } from 'fs';\nimport { cwd, exit, existsSync } from '../node-compat.js';\nimport { getUnifiedMemory } from '../../memory/unified-memory-manager.js';\nimport { KeyRedactor } from '../../utils/key-redactor.js';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nexport async function memoryCommand(subArgs, flags) {\n const memorySubcommand = subArgs[0];\n const memoryStore = './memory/memory-store.json';\n\n // Extract namespace from flags or subArgs\n const namespace = flags?.namespace || flags?.ns || getNamespaceFromArgs(subArgs) || 'default';\n\n // Check for redaction flag\n const enableRedaction = flags?.redact || subArgs.includes('--redact') || subArgs.includes('--secure');\n\n // NEW: Detect memory mode (basic, reasoningbank, auto)\n const mode = await detectMemoryMode(flags, subArgs);\n\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile(memoryStore, 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n\n // Helper to save memory data\n async function saveMemory(data) {\n await fs.mkdir('./memory', { recursive: true });\n await fs.writeFile(memoryStore, JSON.stringify(data, null, 2, 'utf8'));\n }\n\n // NEW: Handle ReasoningBank-specific commands\n if (mode === 'reasoningbank' && ['init', 'status', 'consolidate', 'demo', 'test', 'benchmark'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Handle new mode management commands\n if (['detect', 'mode', 'migrate'].includes(memorySubcommand)) {\n return await handleModeCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Delegate to ReasoningBank for regular commands if mode is set\n if (mode === 'reasoningbank' && ['store', 'query', 'list'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n switch (memorySubcommand) {\n case 'store':\n await storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction);\n break;\n\n case 'query':\n await queryMemory(subArgs, loadMemory, namespace, enableRedaction);\n break;\n\n case 'stats':\n await showMemoryStats(loadMemory);\n break;\n\n case 'export':\n await exportMemory(subArgs, loadMemory, namespace);\n break;\n\n case 'import':\n await importMemory(subArgs, saveMemory, loadMemory);\n break;\n\n case 'clear':\n await clearMemory(subArgs, saveMemory, namespace);\n break;\n\n case 'list':\n await listNamespaces(loadMemory);\n break;\n\n default:\n showMemoryHelp();\n }\n}\n\nasync function storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction = false) {\n const key = subArgs[1];\n let value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n // Apply redaction if enabled\n let redactedValue = value;\n let securityWarnings = [];\n\n if (enableRedaction) {\n redactedValue = KeyRedactor.redact(value, true);\n const validation = KeyRedactor.validate(value);\n\n if (!validation.safe) {\n securityWarnings = validation.warnings;\n printWarning('š Redaction enabled: Sensitive data detected and redacted');\n securityWarnings.forEach(warning => console.log(` ā ļø ${warning}`));\n }\n } else {\n // Even if redaction is not explicitly enabled, validate and warn\n const validation = KeyRedactor.validate(value);\n if (!validation.safe) {\n printWarning('ā ļø Potential sensitive data detected! Use --redact flag for automatic redaction');\n validation.warnings.forEach(warning => console.log(` ā ļø ${warning}`));\n console.log(' š” Tip: Add --redact flag to automatically redact API keys');\n }\n }\n\n const data = await loadMemory();\n\n if (!data[namespace]) {\n data[namespace] = [];\n }\n\n // Remove existing entry with same key\n data[namespace] = data[namespace].filter((e) => e.key !== key);\n\n // Add new entry with redacted value\n data[namespace].push({\n key,\n value: redactedValue,\n namespace,\n timestamp: Date.now(),\n redacted: enableRedaction && securityWarnings.length > 0,\n });\n\n await saveMemory(data);\n printSuccess(enableRedaction && securityWarnings.length > 0 ? 'š Stored successfully (with redaction)' : 'ā
Stored successfully');\n console.log(`š Key: ${key}`);\n console.log(`š¦ Namespace: ${namespace}`);\n console.log(`š¾ Size: ${new TextEncoder().encode(redactedValue).length} bytes`);\n if (enableRedaction && securityWarnings.length > 0) {\n console.log(`š Security: ${securityWarnings.length} sensitive pattern(s) redacted`);\n }\n } catch (err) {\n printError(`Failed to store: ${err.message}`);\n }\n}\n\nasync function queryMemory(subArgs, loadMemory, namespace, enableRedaction = false) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n const data = await loadMemory();\n const results = [];\n\n for (const [ns, entries] of Object.entries(data)) {\n if (namespace && ns !== namespace) continue;\n\n for (const entry of entries) {\n if (entry.key.includes(search) || entry.value.includes(search)) {\n results.push(entry);\n }\n }\n }\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results:`);\n\n // Sort by timestamp (newest first)\n results.sort((a, b) => b.timestamp - a.timestamp);\n\n for (const entry of results.slice(0, 10)) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n\n // Apply redaction to displayed value if requested\n let displayValue = entry.value;\n if (enableRedaction) {\n displayValue = KeyRedactor.redact(displayValue, true);\n }\n\n console.log(\n ` Value: ${displayValue.substring(0, 100)}${displayValue.length > 100 ? '...' : ''}`,\n );\n console.log(` Stored: ${new Date(entry.timestamp).toLocaleString()}`);\n\n // Show redaction status\n if (entry.redacted) {\n console.log(` š Status: Redacted on storage`);\n } else if (enableRedaction) {\n console.log(` š Status: Redacted for display`);\n }\n }\n\n if (results.length > 10) {\n console.log(`\\n... and ${results.length - 10} more results`);\n }\n } catch (err) {\n printError(`Failed to query: ${err.message}`);\n }\n}\n\nasync function showMemoryStats(loadMemory) {\n try {\n const data = await loadMemory();\n let totalEntries = 0;\n const namespaceStats = {};\n\n for (const [namespace, entries] of Object.entries(data)) {\n namespaceStats[namespace] = entries.length;\n totalEntries += entries.length;\n }\n\n printSuccess('Memory Bank Statistics:');\n console.log(` Total Entries: ${totalEntries}`);\n console.log(` Namespaces: ${Object.keys(data).length}`);\n console.log(\n ` Size: ${(new TextEncoder().encode(JSON.stringify(data)).length / 1024).toFixed(2)} KB`,\n );\n\n if (Object.keys(data).length > 0) {\n console.log('\\nš Namespace Breakdown:');\n for (const [namespace, count] of Object.entries(namespaceStats)) {\n console.log(` ${namespace}: ${count} entries`);\n }\n }\n } catch (err) {\n printError(`Failed to get stats: ${err.message}`);\n }\n}\n\nasync function exportMemory(subArgs, loadMemory, namespace) {\n const filename = subArgs[1] || `memory-export-${Date.now()}.json`;\n\n try {\n const data = await loadMemory();\n\n let exportData = data;\n if (namespace) {\n exportData = { [namespace]: data[namespace] || [] };\n }\n\n await fs.writeFile(filename, JSON.stringify(exportData, null, 2, 'utf8'));\n printSuccess(`Memory exported to ${filename}`);\n\n let totalEntries = 0;\n for (const entries of Object.values(exportData)) {\n totalEntries += entries.length;\n }\n console.log(\n `š¦ Exported ${totalEntries} entries from ${Object.keys(exportData).length} namespace(s)`,\n );\n } catch (err) {\n printError(`Failed to export memory: ${err.message}`);\n }\n}\n\nasync function importMemory(subArgs, saveMemory, loadMemory) {\n const filename = subArgs[1];\n\n if (!filename) {\n printError('Usage: memory import <filename>');\n return;\n }\n\n try {\n const importContent = await fs.readFile(filename, 'utf8');\n const importData = JSON.parse(importContent);\n\n // Load existing memory\n const existingData = await loadMemory();\n\n // Merge imported data\n let totalImported = 0;\n for (const [namespace, entries] of Object.entries(importData)) {\n if (!existingData[namespace]) {\n existingData[namespace] = [];\n }\n\n // Add entries that don't already exist (by key)\n const existingKeys = new Set(existingData[namespace].map((e) => e.key));\n const newEntries = entries.filter((e) => !existingKeys.has(e.key));\n\n existingData[namespace].push(...newEntries);\n totalImported += newEntries.length;\n }\n\n await saveMemory(existingData);\n printSuccess(`Imported ${totalImported} new entries from ${filename}`);\n } catch (err) {\n printError(`Failed to import memory: ${err.message}`);\n }\n}\n\nasync function clearMemory(subArgs, saveMemory, namespace) {\n if (!namespace || namespace === 'default') {\n const nsFromArgs = getNamespaceFromArgs(subArgs);\n if (!nsFromArgs) {\n printError('Usage: memory clear --namespace <namespace>');\n printWarning('This will clear all entries in the specified namespace');\n return;\n }\n namespace = nsFromArgs;\n }\n\n try {\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n \n const data = await loadMemory();\n\n if (!data[namespace]) {\n printWarning(`Namespace '${namespace}' does not exist`);\n return;\n }\n\n const entryCount = data[namespace].length;\n delete data[namespace];\n\n await saveMemory(data);\n printSuccess(`Cleared ${entryCount} entries from namespace '${namespace}'`);\n } catch (err) {\n printError(`Failed to clear memory: ${err.message}`);\n }\n}\n\nasync function listNamespaces(loadMemory) {\n try {\n const data = await loadMemory();\n const namespaces = Object.keys(data);\n\n if (namespaces.length === 0) {\n printWarning('No namespaces found');\n return;\n }\n\n printSuccess('Available namespaces:');\n for (const namespace of namespaces) {\n const count = data[namespace].length;\n console.log(` ${namespace} (${count} entries)`);\n }\n } catch (err) {\n printError(`Failed to list namespaces: ${err.message}`);\n }\n}\n\nfunction getNamespaceFromArgs(subArgs) {\n const namespaceIndex = subArgs.indexOf('--namespace');\n if (namespaceIndex !== -1 && namespaceIndex + 1 < subArgs.length) {\n return subArgs[namespaceIndex + 1];\n }\n\n const nsIndex = subArgs.indexOf('--ns');\n if (nsIndex !== -1 && nsIndex + 1 < subArgs.length) {\n return subArgs[nsIndex + 1];\n }\n\n return null;\n}\n\n// Helper to load memory data (needed for import function)\nasync function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n}\n\n// NEW: Mode detection function\nasync function detectMemoryMode(flags, subArgs) {\n // Explicit ReasoningBank flag takes precedence\n if (flags?.reasoningbank || flags?.rb || subArgs.includes('--reasoningbank') || subArgs.includes('--rb')) {\n return 'reasoningbank';\n }\n\n // Auto mode: detect if ReasoningBank is initialized\n if (flags?.auto || subArgs.includes('--auto')) {\n const initialized = await isReasoningBankInitialized();\n return initialized ? 'reasoningbank' : 'basic';\n }\n\n // Default: basic mode (backward compatible)\n return 'basic';\n}\n\n// NEW: Check if ReasoningBank is initialized\nasync function isReasoningBankInitialized() {\n try {\n // Check if .swarm/memory.db exists\n const dbPath = '.swarm/memory.db';\n await fs.access(dbPath);\n return true;\n } catch {\n return false;\n }\n}\n\n// NEW: Handle ReasoningBank commands\nasync function handleReasoningBankCommand(command, subArgs, flags) {\n const initialized = await isReasoningBankInitialized();\n\n // Lazy load the adapter (ES modules)\n const { initializeReasoningBank, storeMemory, queryMemories, listMemories, getStatus, checkReasoningBankTables, migrateReasoningBank } = await import('../../reasoningbank/reasoningbank-adapter.js');\n\n // Special handling for 'init' command\n if (command === 'init') {\n const dbPath = '.swarm/memory.db';\n\n if (initialized) {\n // Database exists - check if migration is needed\n printInfo('š Checking existing database for ReasoningBank schema...\\n');\n\n try {\n // Set the database path for ReasoningBank\n process.env.CLAUDE_FLOW_DB_PATH = dbPath;\n\n const tableCheck = await checkReasoningBankTables();\n\n if (tableCheck.exists) {\n printSuccess('ā
ReasoningBank already complete');\n console.log('Database: .swarm/memory.db');\n console.log('All ReasoningBank tables present\\n');\n console.log('Use --reasoningbank flag with memory commands to enable AI features');\n return;\n }\n\n // Missing tables found - run migration\n console.log(`š Migrating database: ${tableCheck.missingTables.length} tables missing`);\n console.log(` Missing: ${tableCheck.missingTables.join(', ')}\\n`);\n\n const migrationResult = await migrateReasoningBank();\n\n if (migrationResult.success) {\n printSuccess(`ā Migration complete: added ${migrationResult.addedTables?.length || 0} tables`);\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } else {\n printError(`ā Migration failed: ${migrationResult.message}`);\n console.log('Try running: init --force to reinitialize');\n }\n } catch (error) {\n printError('ā Migration check failed');\n console.error(error.message);\n console.log('\\nTry running: init --force to reinitialize');\n }\n return;\n }\n\n // Fresh initialization\n printInfo('š§ Initializing ReasoningBank...');\n console.log('This will create: .swarm/memory.db\\n');\n\n try {\n await initializeReasoningBank();\n printSuccess('ā
ReasoningBank initialized successfully!');\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } catch (error) {\n printError('ā Failed to initialize ReasoningBank');\n console.error(error.message);\n }\n return;\n }\n\n // All other commands require initialization\n if (!initialized) {\n printError('ā ReasoningBank not initialized');\n console.log('\\nTo use ReasoningBank mode, first run:');\n console.log(' memory init --reasoningbank\\n');\n return;\n }\n\n printInfo(`š§ Using ReasoningBank mode...`);\n\n try {\n // Handle different commands\n switch (command) {\n case 'store':\n await handleReasoningBankStore(subArgs, flags, storeMemory);\n break;\n\n case 'query':\n await handleReasoningBankQuery(subArgs, flags, queryMemories);\n break;\n\n case 'list':\n await handleReasoningBankList(subArgs, flags, listMemories);\n break;\n\n case 'status':\n await handleReasoningBankStatus(getStatus);\n break;\n\n case 'consolidate':\n case 'demo':\n case 'test':\n case 'benchmark':\n // These still use CLI commands\n const cmd = `npx agentic-flow reasoningbank ${command}`;\n const { stdout } = await execAsync(cmd, { timeout: 60000 });\n if (stdout) console.log(stdout);\n break;\n\n default:\n printError(`Unknown ReasoningBank command: ${command}`);\n }\n } catch (error) {\n printError(`ā ReasoningBank command failed`);\n console.error(error.message);\n }\n}\n\n// NEW: Handle ReasoningBank store\nasync function handleReasoningBankStore(subArgs, flags, storeMemory) {\n const key = subArgs[1];\n const value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace') || 'default';\n\n const memoryId = await storeMemory(key, value, {\n namespace,\n agent: 'memory-agent',\n domain: namespace,\n });\n\n printSuccess('ā
Stored successfully in ReasoningBank');\n console.log(`š Key: ${key}`);\n console.log(`š§ Memory ID: ${memoryId}`);\n console.log(`š¦ Namespace: ${namespace}`);\n console.log(`š¾ Size: ${new TextEncoder().encode(value).length} bytes`);\n console.log(`š Semantic search: enabled`);\n } catch (error) {\n printError(`Failed to store: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank query\nasync function handleReasoningBankQuery(subArgs, flags, queryMemories) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace');\n const results = await queryMemories(search, {\n domain: namespace || 'general',\n limit: 10,\n });\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results (semantic search):`);\n\n for (const entry of results) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n console.log(` Value: ${entry.value.substring(0, 100)}${entry.value.length > 100 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}%`);\n console.log(` Usage: ${entry.usage_count} times`);\n if (entry.score) {\n console.log(` Match Score: ${(entry.score * 100).toFixed(1)}%`);\n }\n console.log(` Stored: ${new Date(entry.created_at).toLocaleString()}`);\n }\n } catch (error) {\n printError(`Failed to query: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank list\nasync function handleReasoningBankList(subArgs, flags, listMemories) {\n try {\n const sort = flags?.sort || getArgValue(subArgs, '--sort') || 'created_at';\n const limit = parseInt(flags?.limit || getArgValue(subArgs, '--limit') || '10');\n\n const results = await listMemories({ sort, limit });\n\n if (results.length === 0) {\n printWarning('No memories found');\n return;\n }\n\n printSuccess(`ReasoningBank memories (${results.length} shown):`);\n\n for (const entry of results) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Value: ${entry.value.substring(0, 80)}${entry.value.length > 80 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}% | Usage: ${entry.usage_count}`);\n }\n } catch (error) {\n printError(`Failed to list: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank status\nasync function handleReasoningBankStatus(getStatus) {\n try {\n const stats = await getStatus();\n\n printSuccess('š ReasoningBank Status:');\n console.log(` Total memories: ${stats.total_memories}`);\n console.log(` Average confidence: ${(stats.avg_confidence * 100).toFixed(1)}%`);\n console.log(` Total usage: ${stats.total_usage}`);\n console.log(` Embeddings: ${stats.total_embeddings}`);\n console.log(` Trajectories: ${stats.total_trajectories}`);\n } catch (error) {\n printError(`Failed to get status: ${error.message}`);\n }\n}\n\n// NEW: Build agentic-flow reasoningbank command\nfunction buildReasoningBankCommand(command, subArgs, flags) {\n const parts = ['npx', 'agentic-flow', 'reasoningbank'];\n\n // Map memory commands to reasoningbank commands\n const commandMap = {\n store: 'store',\n query: 'query',\n list: 'list',\n status: 'status',\n consolidate: 'consolidate',\n demo: 'demo',\n test: 'test',\n benchmark: 'benchmark',\n };\n\n parts.push(commandMap[command] || command);\n\n // Add arguments (skip the command itself)\n const args = subArgs.slice(1);\n args.forEach((arg) => {\n if (!arg.startsWith('--reasoningbank') && !arg.startsWith('--rb') && !arg.startsWith('--auto')) {\n parts.push(`\"${arg}\"`);\n }\n });\n\n // Add required --agent parameter\n parts.push('--agent', 'memory-agent');\n\n return parts.join(' ');\n}\n\n// NEW: Handle mode management commands\nasync function handleModeCommand(command, subArgs, flags) {\n switch (command) {\n case 'detect':\n await detectModes();\n break;\n\n case 'mode':\n await showCurrentMode();\n break;\n\n case 'migrate':\n await migrateMemory(subArgs, flags);\n break;\n\n default:\n printError(`Unknown mode command: ${command}`);\n }\n}\n\n// NEW: Detect and show available memory modes\nasync function detectModes() {\n printInfo('š Detecting memory modes...\\n');\n\n // Check basic mode\n const basicAvailable = await checkBasicMode();\n console.log(basicAvailable ? 'ā
Basic Mode (active)' : 'ā Basic Mode (unavailable)');\n if (basicAvailable) {\n console.log(' Location: ./memory/memory-store.json');\n console.log(' Features: Simple key-value storage, fast');\n }\n\n console.log('');\n\n // Check ReasoningBank mode\n const rbAvailable = await isReasoningBankInitialized();\n console.log(rbAvailable ? 'ā
ReasoningBank Mode (available)' : 'ā ļø ReasoningBank Mode (not initialized)');\n if (rbAvailable) {\n console.log(' Location: .swarm/memory.db');\n console.log(' Features: AI-powered semantic search, learning');\n } else {\n console.log(' To enable: memory init --reasoningbank');\n }\n\n console.log('\\nš” Usage:');\n console.log(' Basic: memory store key \"value\"');\n console.log(' ReasoningBank: memory store key \"value\" --reasoningbank');\n console.log(' Auto-detect: memory query search --auto');\n}\n\n// NEW: Check if basic mode is available\nasync function checkBasicMode() {\n try {\n const memoryDir = './memory';\n await fs.access(memoryDir);\n return true;\n } catch {\n // Create directory if it doesn't exist\n try {\n await fs.mkdir(memoryDir, { recursive: true });\n return true;\n } catch {\n return false;\n }\n }\n}\n\n// NEW: Show current default mode\nasync function showCurrentMode() {\n const rbInitialized = await isReasoningBankInitialized();\n\n printInfo('š Current Memory Configuration:\\n');\n console.log('Default Mode: Basic (backward compatible)');\n console.log('Available Modes:');\n console.log(' ⢠Basic Mode: Always available');\n console.log(` ⢠ReasoningBank Mode: ${rbInitialized ? 'Initialized ā
' : 'Not initialized ā ļø'}`);\n\n console.log('\\nš” To use a specific mode:');\n console.log(' --reasoningbank or --rb ā Use ReasoningBank');\n console.log(' --auto ā Auto-detect best mode');\n console.log(' (no flag) ā Use Basic mode');\n}\n\n// NEW: Migrate memory between modes\nasync function migrateMemory(subArgs, flags) {\n const targetMode = flags?.to || getArgValue(subArgs, '--to');\n\n if (!targetMode || !['basic', 'reasoningbank'].includes(targetMode)) {\n printError('Usage: memory migrate --to <basic|reasoningbank>');\n return;\n }\n\n printInfo(`š Migrating to ${targetMode} mode...\\n`);\n\n if (targetMode === 'reasoningbank') {\n // Migrate basic ā ReasoningBank\n const rbInitialized = await isReasoningBankInitialized();\n if (!rbInitialized) {\n printError('ā ReasoningBank not initialized');\n console.log('First run: memory init --reasoningbank\\n');\n return;\n }\n\n printWarning('ā ļø Migration from basic to ReasoningBank is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n console.log('For now, you can:');\n console.log(' 1. Export basic memory: memory export backup.json');\n console.log(' 2. Manually import to ReasoningBank');\n } else {\n // Migrate ReasoningBank ā basic\n printWarning('ā ļø Migration from ReasoningBank to basic is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n }\n}\n\n// Helper to get argument value\nfunction getArgValue(args, flag) {\n const index = args.indexOf(flag);\n if (index !== -1 && index + 1 < args.length) {\n return args[index + 1];\n }\n return null;\n}\n\nfunction showMemoryHelp() {\n console.log('Memory commands:');\n console.log(' store <key> <value> Store a key-value pair');\n console.log(' query <search> Search for entries');\n console.log(' stats Show memory statistics');\n console.log(' export [filename] Export memory to file');\n console.log(' import <filename> Import memory from file');\n console.log(' clear --namespace <ns> Clear a namespace');\n console.log(' list List all namespaces');\n console.log();\n console.log('š§ ReasoningBank Commands (NEW in v2.7.0):');\n console.log(' init --reasoningbank Initialize ReasoningBank (AI-powered memory)');\n console.log(' status --reasoningbank Show ReasoningBank statistics');\n console.log(' detect Show available memory modes');\n console.log(' mode Show current memory configuration');\n console.log(' migrate --to <mode> Migrate between basic/reasoningbank');\n console.log();\n console.log('Options:');\n console.log(' --namespace <ns> Specify namespace for operations');\n console.log(' --ns <ns> Short form of --namespace');\n console.log(' --redact š Enable API key redaction (security feature)');\n console.log(' --secure Alias for --redact');\n console.log();\n console.log('šÆ Mode Selection (NEW):');\n console.log(' --reasoningbank, --rb Use ReasoningBank mode (AI-powered)');\n console.log(' --auto Auto-detect best available mode');\n console.log(' (no flag) Use Basic mode (default, backward compatible)');\n console.log();\n console.log('š Security Features (v2.6.0):');\n console.log(' API Key Protection: Automatically detects and redacts sensitive data');\n console.log(' Patterns Detected: Anthropic, OpenRouter, Gemini, Bearer tokens, etc.');\n console.log(' Auto-Validation: Warns when storing unredacted sensitive data');\n console.log(' Display Redaction: Redact sensitive data when querying with --redact');\n console.log();\n console.log('Examples:');\n console.log(' # Basic mode (default - backward compatible)');\n console.log(' memory store previous_work \"Research findings from yesterday\"');\n console.log(' memory store api_config \"key=sk-ant-...\" --redact # š Redacts API key');\n console.log(' memory query research --namespace sparc');\n console.log();\n console.log(' # ReasoningBank mode (AI-powered, opt-in)');\n console.log(' memory init --reasoningbank # One-time setup');\n console.log(' memory store api_pattern \"Always use env vars\" --reasoningbank');\n console.log(' memory query \"API configuration\" --reasoningbank # Semantic search!');\n console.log(' memory status --reasoningbank # Show AI metrics');\n console.log();\n console.log(' # Auto-detect mode (smart selection)');\n console.log(' memory query config --auto # Uses ReasoningBank if available');\n console.log();\n console.log(' # Mode management');\n console.log(' memory detect # Show available modes');\n console.log(' memory mode # Show current configuration');\n console.log();\n console.log('š” Tips:');\n console.log(' ⢠Use Basic mode for simple key-value storage (fast, always available)');\n console.log(' ⢠Use ReasoningBank for AI-powered semantic search (learns from patterns)');\n console.log(' ⢠Use --auto to let claude-flow choose the best mode for you');\n console.log(' ⢠Always use --redact when storing API keys or secrets!');\n}\n"],"names":["printSuccess","printError","printWarning","printInfo","promises","fs","KeyRedactor","exec","promisify","execAsync","memoryCommand","subArgs","flags","memorySubcommand","memoryStore","namespace","ns","getNamespaceFromArgs","enableRedaction","redact","includes","mode","detectMemoryMode","loadMemory","content","readFile","JSON","parse","saveMemory","data","mkdir","recursive","writeFile","stringify","handleReasoningBankCommand","handleModeCommand","storeMemory","queryMemory","showMemoryStats","exportMemory","importMemory","clearMemory","listNamespaces","showMemoryHelp","key","value","slice","join","redactedValue","securityWarnings","validation","validate","safe","warnings","forEach","warning","console","log","filter","e","push","timestamp","Date","now","redacted","length","TextEncoder","encode","err","message","search","results","entries","Object","entry","sort","a","b","displayValue","substring","toLocaleString","totalEntries","namespaceStats","keys","toFixed","count","filename","exportData","values","importContent","importData","existingData","totalImported","existingKeys","Set","map","newEntries","has","nsFromArgs","entryCount","namespaces","namespaceIndex","indexOf","nsIndex","reasoningbank","rb","auto","initialized","isReasoningBankInitialized","dbPath","access","command","initializeReasoningBank","queryMemories","listMemories","getStatus","checkReasoningBankTables","migrateReasoningBank","process","env","CLAUDE_FLOW_DB_PATH","tableCheck","exists","missingTables","migrationResult","success","addedTables","error","handleReasoningBankStore","handleReasoningBankQuery","handleReasoningBankList","handleReasoningBankStatus","cmd","stdout","timeout","getArgValue","memoryId","agent","domain","limit","confidence","usage_count","score","created_at","parseInt","stats","total_memories","avg_confidence","total_usage","total_embeddings","total_trajectories","buildReasoningBankCommand","parts","commandMap","store","query","list","status","consolidate","demo","test","benchmark","args","arg","startsWith","detectModes","showCurrentMode","migrateMemory","basicAvailable","checkBasicMode","rbAvailable","memoryDir","rbInitialized","targetMode","to","flag","index"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,EAAEC,SAAS,QAAQ,cAAc;AAChF,SAASC,YAAYC,EAAE,QAAQ,KAAK;AAGpC,SAASC,WAAW,QAAQ,8BAA8B;AAC1D,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AAEjC,MAAMC,YAAYD,UAAUD;AAE5B,OAAO,eAAeG,cAAcC,OAAO,EAAEC,KAAK;IAChD,MAAMC,mBAAmBF,OAAO,CAAC,EAAE;IACnC,MAAMG,cAAc;IAGpB,MAAMC,YAAYH,OAAOG,aAAaH,OAAOI,MAAMC,qBAAqBN,YAAY;IAGpF,MAAMO,kBAAkBN,OAAOO,UAAUR,QAAQS,QAAQ,CAAC,eAAeT,QAAQS,QAAQ,CAAC;IAG1F,MAAMC,OAAO,MAAMC,iBAAiBV,OAAOD;IAG3C,eAAeY;QACb,IAAI;YACF,MAAMC,UAAU,MAAMnB,GAAGoB,QAAQ,CAACX,aAAa;YAC/C,OAAOY,KAAKC,KAAK,CAACH;QACpB,EAAE,OAAM;YACN,OAAO,CAAC;QACV;IACF;IAGA,eAAeI,WAAWC,IAAI;QAC5B,MAAMxB,GAAGyB,KAAK,CAAC,YAAY;YAAEC,WAAW;QAAK;QAC7C,MAAM1B,GAAG2B,SAAS,CAAClB,aAAaY,KAAKO,SAAS,CAACJ,MAAM,MAAM,GAAG;IAChE;IAGA,IAAIR,SAAS,mBAAmB;QAAC;QAAQ;QAAU;QAAe;QAAQ;QAAQ;KAAY,CAACD,QAAQ,CAACP,mBA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C,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/cli/simple-commands/memory.js"],"sourcesContent":["// memory.js - Memory management commands\nimport { printSuccess, printError, printWarning, printInfo } from '../utils.js';\nimport { promises as fs } from 'fs';\nimport { cwd, exit, existsSync } from '../node-compat.js';\nimport { getUnifiedMemory } from '../../memory/unified-memory-manager.js';\nimport { KeyRedactor } from '../../utils/key-redactor.js';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nexport async function memoryCommand(subArgs, flags) {\n const memorySubcommand = subArgs[0];\n const memoryStore = './memory/memory-store.json';\n\n // Extract namespace from flags or subArgs\n const namespace = flags?.namespace || flags?.ns || getNamespaceFromArgs(subArgs) || 'default';\n\n // Check for redaction flag\n const enableRedaction = flags?.redact || subArgs.includes('--redact') || subArgs.includes('--secure');\n\n // NEW: Detect memory mode (basic, reasoningbank, auto)\n const mode = await detectMemoryMode(flags, subArgs);\n\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile(memoryStore, 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n\n // Helper to save memory data\n async function saveMemory(data) {\n await fs.mkdir('./memory', { recursive: true });\n await fs.writeFile(memoryStore, JSON.stringify(data, null, 2, 'utf8'));\n }\n\n // NEW: Handle ReasoningBank-specific commands\n if (mode === 'reasoningbank' && ['init', 'status', 'consolidate', 'demo', 'test', 'benchmark'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Handle new mode management commands\n if (['detect', 'mode', 'migrate'].includes(memorySubcommand)) {\n return await handleModeCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Delegate to ReasoningBank for regular commands if mode is set\n if (mode === 'reasoningbank' && ['store', 'query', 'list'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n switch (memorySubcommand) {\n case 'store':\n await storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction);\n break;\n\n case 'query':\n await queryMemory(subArgs, loadMemory, namespace, enableRedaction);\n break;\n\n case 'stats':\n await showMemoryStats(loadMemory);\n break;\n\n case 'export':\n await exportMemory(subArgs, loadMemory, namespace);\n break;\n\n case 'import':\n await importMemory(subArgs, saveMemory, loadMemory);\n break;\n\n case 'clear':\n await clearMemory(subArgs, saveMemory, namespace);\n break;\n\n case 'list':\n await listNamespaces(loadMemory);\n break;\n\n default:\n showMemoryHelp();\n }\n}\n\nasync function storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction = false) {\n const key = subArgs[1];\n let value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n // Apply redaction if enabled\n let redactedValue = value;\n let securityWarnings = [];\n\n if (enableRedaction) {\n redactedValue = KeyRedactor.redact(value, true);\n const validation = KeyRedactor.validate(value);\n\n if (!validation.safe) {\n securityWarnings = validation.warnings;\n printWarning('š Redaction enabled: Sensitive data detected and redacted');\n securityWarnings.forEach(warning => console.log(` ā ļø ${warning}`));\n }\n } else {\n // Even if redaction is not explicitly enabled, validate and warn\n const validation = KeyRedactor.validate(value);\n if (!validation.safe) {\n printWarning('ā ļø Potential sensitive data detected! Use --redact flag for automatic redaction');\n validation.warnings.forEach(warning => console.log(` ā ļø ${warning}`));\n console.log(' š” Tip: Add --redact flag to automatically redact API keys');\n }\n }\n\n const data = await loadMemory();\n\n if (!data[namespace]) {\n data[namespace] = [];\n }\n\n // Remove existing entry with same key\n data[namespace] = data[namespace].filter((e) => e.key !== key);\n\n // Add new entry with redacted value\n data[namespace].push({\n key,\n value: redactedValue,\n namespace,\n timestamp: Date.now(),\n redacted: enableRedaction && securityWarnings.length > 0,\n });\n\n await saveMemory(data);\n printSuccess(enableRedaction && securityWarnings.length > 0 ? 'š Stored successfully (with redaction)' : 'ā
Stored successfully');\n console.log(`š Key: ${key}`);\n console.log(`š¦ Namespace: ${namespace}`);\n console.log(`š¾ Size: ${new TextEncoder().encode(redactedValue).length} bytes`);\n if (enableRedaction && securityWarnings.length > 0) {\n console.log(`š Security: ${securityWarnings.length} sensitive pattern(s) redacted`);\n }\n } catch (err) {\n printError(`Failed to store: ${err.message}`);\n }\n}\n\nasync function queryMemory(subArgs, loadMemory, namespace, enableRedaction = false) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n const data = await loadMemory();\n const results = [];\n\n for (const [ns, entries] of Object.entries(data)) {\n if (namespace && ns !== namespace) continue;\n\n for (const entry of entries) {\n if (entry.key.includes(search) || entry.value.includes(search)) {\n results.push(entry);\n }\n }\n }\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results:`);\n\n // Sort by timestamp (newest first)\n results.sort((a, b) => b.timestamp - a.timestamp);\n\n for (const entry of results.slice(0, 10)) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n\n // Apply redaction to displayed value if requested\n let displayValue = entry.value;\n if (enableRedaction) {\n displayValue = KeyRedactor.redact(displayValue, true);\n }\n\n console.log(\n ` Value: ${displayValue.substring(0, 100)}${displayValue.length > 100 ? '...' : ''}`,\n );\n console.log(` Stored: ${new Date(entry.timestamp).toLocaleString()}`);\n\n // Show redaction status\n if (entry.redacted) {\n console.log(` š Status: Redacted on storage`);\n } else if (enableRedaction) {\n console.log(` š Status: Redacted for display`);\n }\n }\n\n if (results.length > 10) {\n console.log(`\\n... and ${results.length - 10} more results`);\n }\n } catch (err) {\n printError(`Failed to query: ${err.message}`);\n }\n}\n\nasync function showMemoryStats(loadMemory) {\n try {\n const data = await loadMemory();\n let totalEntries = 0;\n const namespaceStats = {};\n\n for (const [namespace, entries] of Object.entries(data)) {\n namespaceStats[namespace] = entries.length;\n totalEntries += entries.length;\n }\n\n printSuccess('Memory Bank Statistics:');\n console.log(` Total Entries: ${totalEntries}`);\n console.log(` Namespaces: ${Object.keys(data).length}`);\n console.log(\n ` Size: ${(new TextEncoder().encode(JSON.stringify(data)).length / 1024).toFixed(2)} KB`,\n );\n\n if (Object.keys(data).length > 0) {\n console.log('\\nš Namespace Breakdown:');\n for (const [namespace, count] of Object.entries(namespaceStats)) {\n console.log(` ${namespace}: ${count} entries`);\n }\n }\n } catch (err) {\n printError(`Failed to get stats: ${err.message}`);\n }\n}\n\nasync function exportMemory(subArgs, loadMemory, namespace) {\n const filename = subArgs[1] || `memory-export-${Date.now()}.json`;\n\n try {\n const data = await loadMemory();\n\n let exportData = data;\n if (namespace) {\n exportData = { [namespace]: data[namespace] || [] };\n }\n\n await fs.writeFile(filename, JSON.stringify(exportData, null, 2, 'utf8'));\n printSuccess(`Memory exported to ${filename}`);\n\n let totalEntries = 0;\n for (const entries of Object.values(exportData)) {\n totalEntries += entries.length;\n }\n console.log(\n `š¦ Exported ${totalEntries} entries from ${Object.keys(exportData).length} namespace(s)`,\n );\n } catch (err) {\n printError(`Failed to export memory: ${err.message}`);\n }\n}\n\nasync function importMemory(subArgs, saveMemory, loadMemory) {\n const filename = subArgs[1];\n\n if (!filename) {\n printError('Usage: memory import <filename>');\n return;\n }\n\n try {\n const importContent = await fs.readFile(filename, 'utf8');\n const importData = JSON.parse(importContent);\n\n // Load existing memory\n const existingData = await loadMemory();\n\n // Merge imported data\n let totalImported = 0;\n for (const [namespace, entries] of Object.entries(importData)) {\n if (!existingData[namespace]) {\n existingData[namespace] = [];\n }\n\n // Add entries that don't already exist (by key)\n const existingKeys = new Set(existingData[namespace].map((e) => e.key));\n const newEntries = entries.filter((e) => !existingKeys.has(e.key));\n\n existingData[namespace].push(...newEntries);\n totalImported += newEntries.length;\n }\n\n await saveMemory(existingData);\n printSuccess(`Imported ${totalImported} new entries from ${filename}`);\n } catch (err) {\n printError(`Failed to import memory: ${err.message}`);\n }\n}\n\nasync function clearMemory(subArgs, saveMemory, namespace) {\n if (!namespace || namespace === 'default') {\n const nsFromArgs = getNamespaceFromArgs(subArgs);\n if (!nsFromArgs) {\n printError('Usage: memory clear --namespace <namespace>');\n printWarning('This will clear all entries in the specified namespace');\n return;\n }\n namespace = nsFromArgs;\n }\n\n try {\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n \n const data = await loadMemory();\n\n if (!data[namespace]) {\n printWarning(`Namespace '${namespace}' does not exist`);\n return;\n }\n\n const entryCount = data[namespace].length;\n delete data[namespace];\n\n await saveMemory(data);\n printSuccess(`Cleared ${entryCount} entries from namespace '${namespace}'`);\n } catch (err) {\n printError(`Failed to clear memory: ${err.message}`);\n }\n}\n\nasync function listNamespaces(loadMemory) {\n try {\n const data = await loadMemory();\n const namespaces = Object.keys(data);\n\n if (namespaces.length === 0) {\n printWarning('No namespaces found');\n return;\n }\n\n printSuccess('Available namespaces:');\n for (const namespace of namespaces) {\n const count = data[namespace].length;\n console.log(` ${namespace} (${count} entries)`);\n }\n } catch (err) {\n printError(`Failed to list namespaces: ${err.message}`);\n }\n}\n\nfunction getNamespaceFromArgs(subArgs) {\n const namespaceIndex = subArgs.indexOf('--namespace');\n if (namespaceIndex !== -1 && namespaceIndex + 1 < subArgs.length) {\n return subArgs[namespaceIndex + 1];\n }\n\n const nsIndex = subArgs.indexOf('--ns');\n if (nsIndex !== -1 && nsIndex + 1 < subArgs.length) {\n return subArgs[nsIndex + 1];\n }\n\n return null;\n}\n\n// Helper to load memory data (needed for import function)\nasync function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n}\n\n// NEW: Mode detection function\nasync function detectMemoryMode(flags, subArgs) {\n // Explicit ReasoningBank flag takes precedence\n if (flags?.reasoningbank || flags?.rb || subArgs.includes('--reasoningbank') || subArgs.includes('--rb')) {\n return 'reasoningbank';\n }\n\n // Auto mode: detect if ReasoningBank is initialized\n if (flags?.auto || subArgs.includes('--auto')) {\n const initialized = await isReasoningBankInitialized();\n return initialized ? 'reasoningbank' : 'basic';\n }\n\n // Explicit basic mode flag\n if (flags?.basic || subArgs.includes('--basic')) {\n return 'basic';\n }\n\n // Default: AUTO MODE (smart selection with JSON fallback)\n // Automatically use ReasoningBank if initialized, otherwise fall back to basic mode\n const initialized = await isReasoningBankInitialized();\n return initialized ? 'reasoningbank' : 'basic';\n}\n\n// NEW: Check if ReasoningBank is initialized\nasync function isReasoningBankInitialized() {\n try {\n // Check if .swarm/memory.db exists\n const dbPath = '.swarm/memory.db';\n await fs.access(dbPath);\n return true;\n } catch {\n return false;\n }\n}\n\n// NEW: Handle ReasoningBank commands\nasync function handleReasoningBankCommand(command, subArgs, flags) {\n const initialized = await isReasoningBankInitialized();\n\n // Lazy load the adapter (ES modules)\n const { initializeReasoningBank, storeMemory, queryMemories, listMemories, getStatus, checkReasoningBankTables, migrateReasoningBank } = await import('../../reasoningbank/reasoningbank-adapter.js');\n\n // Special handling for 'init' command\n if (command === 'init') {\n const dbPath = '.swarm/memory.db';\n\n if (initialized) {\n // Database exists - check if migration is needed\n printInfo('š Checking existing database for ReasoningBank schema...\\n');\n\n try {\n // Set the database path for ReasoningBank\n process.env.CLAUDE_FLOW_DB_PATH = dbPath;\n\n const tableCheck = await checkReasoningBankTables();\n\n if (tableCheck.exists) {\n printSuccess('ā
ReasoningBank already complete');\n console.log('Database: .swarm/memory.db');\n console.log('All ReasoningBank tables present\\n');\n console.log('Use --reasoningbank flag with memory commands to enable AI features');\n return;\n }\n\n // Missing tables found - run migration\n console.log(`š Migrating database: ${tableCheck.missingTables.length} tables missing`);\n console.log(` Missing: ${tableCheck.missingTables.join(', ')}\\n`);\n\n const migrationResult = await migrateReasoningBank();\n\n if (migrationResult.success) {\n printSuccess(`ā Migration complete: added ${migrationResult.addedTables?.length || 0} tables`);\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } else {\n printError(`ā Migration failed: ${migrationResult.message}`);\n console.log('Try running: init --force to reinitialize');\n }\n } catch (error) {\n printError('ā Migration check failed');\n console.error(error.message);\n console.log('\\nTry running: init --force to reinitialize');\n }\n return;\n }\n\n // Fresh initialization\n printInfo('š§ Initializing ReasoningBank...');\n console.log('This will create: .swarm/memory.db\\n');\n\n try {\n await initializeReasoningBank();\n printSuccess('ā
ReasoningBank initialized successfully!');\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } catch (error) {\n printError('ā Failed to initialize ReasoningBank');\n console.error(error.message);\n }\n return;\n }\n\n // All other commands require initialization\n if (!initialized) {\n printError('ā ReasoningBank not initialized');\n console.log('\\nTo use ReasoningBank mode, first run:');\n console.log(' memory init --reasoningbank\\n');\n return;\n }\n\n printInfo(`š§ Using ReasoningBank mode...`);\n\n try {\n // Handle different commands\n switch (command) {\n case 'store':\n await handleReasoningBankStore(subArgs, flags, storeMemory);\n break;\n\n case 'query':\n await handleReasoningBankQuery(subArgs, flags, queryMemories);\n break;\n\n case 'list':\n await handleReasoningBankList(subArgs, flags, listMemories);\n break;\n\n case 'status':\n await handleReasoningBankStatus(getStatus);\n break;\n\n case 'consolidate':\n case 'demo':\n case 'test':\n case 'benchmark':\n // These still use CLI commands\n const cmd = `npx agentic-flow reasoningbank ${command}`;\n const { stdout } = await execAsync(cmd, { timeout: 60000 });\n if (stdout) console.log(stdout);\n break;\n\n default:\n printError(`Unknown ReasoningBank command: ${command}`);\n }\n } catch (error) {\n printError(`ā ReasoningBank command failed`);\n console.error(error.message);\n }\n}\n\n// NEW: Handle ReasoningBank store\nasync function handleReasoningBankStore(subArgs, flags, storeMemory) {\n const key = subArgs[1];\n const value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace') || 'default';\n\n const memoryId = await storeMemory(key, value, {\n namespace,\n agent: 'memory-agent',\n domain: namespace,\n });\n\n printSuccess('ā
Stored successfully in ReasoningBank');\n console.log(`š Key: ${key}`);\n console.log(`š§ Memory ID: ${memoryId}`);\n console.log(`š¦ Namespace: ${namespace}`);\n console.log(`š¾ Size: ${new TextEncoder().encode(value).length} bytes`);\n console.log(`š Semantic search: enabled`);\n } catch (error) {\n printError(`Failed to store: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank query\nasync function handleReasoningBankQuery(subArgs, flags, queryMemories) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace');\n const results = await queryMemories(search, {\n domain: namespace || 'general',\n limit: 10,\n });\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results (semantic search):`);\n\n for (const entry of results) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n console.log(` Value: ${entry.value.substring(0, 100)}${entry.value.length > 100 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}%`);\n console.log(` Usage: ${entry.usage_count} times`);\n if (entry.score) {\n console.log(` Match Score: ${(entry.score * 100).toFixed(1)}%`);\n }\n console.log(` Stored: ${new Date(entry.created_at).toLocaleString()}`);\n }\n } catch (error) {\n printError(`Failed to query: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank list\nasync function handleReasoningBankList(subArgs, flags, listMemories) {\n try {\n const sort = flags?.sort || getArgValue(subArgs, '--sort') || 'created_at';\n const limit = parseInt(flags?.limit || getArgValue(subArgs, '--limit') || '10');\n\n const results = await listMemories({ sort, limit });\n\n if (results.length === 0) {\n printWarning('No memories found');\n return;\n }\n\n printSuccess(`ReasoningBank memories (${results.length} shown):`);\n\n for (const entry of results) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Value: ${entry.value.substring(0, 80)}${entry.value.length > 80 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}% | Usage: ${entry.usage_count}`);\n }\n } catch (error) {\n printError(`Failed to list: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank status\nasync function handleReasoningBankStatus(getStatus) {\n try {\n const stats = await getStatus();\n\n printSuccess('š ReasoningBank Status:');\n console.log(` Total memories: ${stats.total_memories}`);\n console.log(` Average confidence: ${(stats.avg_confidence * 100).toFixed(1)}%`);\n console.log(` Total usage: ${stats.total_usage}`);\n console.log(` Embeddings: ${stats.total_embeddings}`);\n console.log(` Trajectories: ${stats.total_trajectories}`);\n } catch (error) {\n printError(`Failed to get status: ${error.message}`);\n }\n}\n\n// NEW: Build agentic-flow reasoningbank command\nfunction buildReasoningBankCommand(command, subArgs, flags) {\n const parts = ['npx', 'agentic-flow', 'reasoningbank'];\n\n // Map memory commands to reasoningbank commands\n const commandMap = {\n store: 'store',\n query: 'query',\n list: 'list',\n status: 'status',\n consolidate: 'consolidate',\n demo: 'demo',\n test: 'test',\n benchmark: 'benchmark',\n };\n\n parts.push(commandMap[command] || command);\n\n // Add arguments (skip the command itself)\n const args = subArgs.slice(1);\n args.forEach((arg) => {\n if (!arg.startsWith('--reasoningbank') && !arg.startsWith('--rb') && !arg.startsWith('--auto')) {\n parts.push(`\"${arg}\"`);\n }\n });\n\n // Add required --agent parameter\n parts.push('--agent', 'memory-agent');\n\n return parts.join(' ');\n}\n\n// NEW: Handle mode management commands\nasync function handleModeCommand(command, subArgs, flags) {\n switch (command) {\n case 'detect':\n await detectModes();\n break;\n\n case 'mode':\n await showCurrentMode();\n break;\n\n case 'migrate':\n await migrateMemory(subArgs, flags);\n break;\n\n default:\n printError(`Unknown mode command: ${command}`);\n }\n}\n\n// NEW: Detect and show available memory modes\nasync function detectModes() {\n printInfo('š Detecting memory modes...\\n');\n\n // Check basic mode\n const basicAvailable = await checkBasicMode();\n console.log(basicAvailable ? 'ā
Basic Mode (active)' : 'ā Basic Mode (unavailable)');\n if (basicAvailable) {\n console.log(' Location: ./memory/memory-store.json');\n console.log(' Features: Simple key-value storage, fast');\n }\n\n console.log('');\n\n // Check ReasoningBank mode\n const rbAvailable = await isReasoningBankInitialized();\n console.log(rbAvailable ? 'ā
ReasoningBank Mode (available)' : 'ā ļø ReasoningBank Mode (not initialized)');\n if (rbAvailable) {\n console.log(' Location: .swarm/memory.db');\n console.log(' Features: AI-powered semantic search, learning');\n } else {\n console.log(' To enable: memory init --reasoningbank');\n }\n\n console.log('\\nš” Usage:');\n console.log(' Basic: memory store key \"value\"');\n console.log(' ReasoningBank: memory store key \"value\" --reasoningbank');\n console.log(' Auto-detect: memory query search --auto');\n}\n\n// NEW: Check if basic mode is available\nasync function checkBasicMode() {\n try {\n const memoryDir = './memory';\n await fs.access(memoryDir);\n return true;\n } catch {\n // Create directory if it doesn't exist\n try {\n await fs.mkdir(memoryDir, { recursive: true });\n return true;\n } catch {\n return false;\n }\n }\n}\n\n// NEW: Show current default mode\nasync function showCurrentMode() {\n const rbInitialized = await isReasoningBankInitialized();\n\n printInfo('š Current Memory Configuration:\\n');\n console.log('Default Mode: AUTO (smart selection with JSON fallback)');\n console.log('Available Modes:');\n console.log(' ⢠Basic Mode: Always available (JSON storage)');\n console.log(` ⢠ReasoningBank Mode: ${rbInitialized ? 'Initialized ā
(will be used by default)' : 'Not initialized ā ļø (JSON fallback active)'}`);\n\n console.log('\\nš” Mode Behavior:');\n console.log(' (no flag) ā AUTO: Use ReasoningBank if initialized, else JSON');\n console.log(' --reasoningbank or --rb ā Force ReasoningBank mode');\n console.log(' --basic ā Force JSON mode');\n console.log(' --auto ā Same as default (explicit)');\n}\n\n// NEW: Migrate memory between modes\nasync function migrateMemory(subArgs, flags) {\n const targetMode = flags?.to || getArgValue(subArgs, '--to');\n\n if (!targetMode || !['basic', 'reasoningbank'].includes(targetMode)) {\n printError('Usage: memory migrate --to <basic|reasoningbank>');\n return;\n }\n\n printInfo(`š Migrating to ${targetMode} mode...\\n`);\n\n if (targetMode === 'reasoningbank') {\n // Migrate basic ā ReasoningBank\n const rbInitialized = await isReasoningBankInitialized();\n if (!rbInitialized) {\n printError('ā ReasoningBank not initialized');\n console.log('First run: memory init --reasoningbank\\n');\n return;\n }\n\n printWarning('ā ļø Migration from basic to ReasoningBank is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n console.log('For now, you can:');\n console.log(' 1. Export basic memory: memory export backup.json');\n console.log(' 2. Manually import to ReasoningBank');\n } else {\n // Migrate ReasoningBank ā basic\n printWarning('ā ļø Migration from ReasoningBank to basic is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n }\n}\n\n// Helper to get argument value\nfunction getArgValue(args, flag) {\n const index = args.indexOf(flag);\n if (index !== -1 && index + 1 < args.length) {\n return args[index + 1];\n }\n return null;\n}\n\nfunction showMemoryHelp() {\n console.log('Memory commands:');\n console.log(' store <key> <value> Store a key-value pair');\n console.log(' query <search> Search for entries');\n console.log(' stats Show memory statistics');\n console.log(' export [filename] Export memory to file');\n console.log(' import <filename> Import memory from file');\n console.log(' clear --namespace <ns> Clear a namespace');\n console.log(' list List all namespaces');\n console.log();\n console.log('š§ ReasoningBank Commands (NEW in v2.7.0):');\n console.log(' init --reasoningbank Initialize ReasoningBank (AI-powered memory)');\n console.log(' status --reasoningbank Show ReasoningBank statistics');\n console.log(' detect Show available memory modes');\n console.log(' mode Show current memory configuration');\n console.log(' migrate --to <mode> Migrate between basic/reasoningbank');\n console.log();\n console.log('Options:');\n console.log(' --namespace <ns> Specify namespace for operations');\n console.log(' --ns <ns> Short form of --namespace');\n console.log(' --redact š Enable API key redaction (security feature)');\n console.log(' --secure Alias for --redact');\n console.log();\n console.log('šÆ Mode Selection:');\n console.log(' (no flag) AUTO MODE (default) - Uses ReasoningBank if initialized, else JSON fallback');\n console.log(' --reasoningbank, --rb Force ReasoningBank mode (AI-powered)');\n console.log(' --basic Force Basic mode (JSON storage)');\n console.log(' --auto Explicit auto-detect (same as default)');\n console.log();\n console.log('š Security Features (v2.6.0):');\n console.log(' API Key Protection: Automatically detects and redacts sensitive data');\n console.log(' Patterns Detected: Anthropic, OpenRouter, Gemini, Bearer tokens, etc.');\n console.log(' Auto-Validation: Warns when storing unredacted sensitive data');\n console.log(' Display Redaction: Redact sensitive data when querying with --redact');\n console.log();\n console.log('Examples:');\n console.log(' # Basic mode (default - backward compatible)');\n console.log(' memory store previous_work \"Research findings from yesterday\"');\n console.log(' memory store api_config \"key=sk-ant-...\" --redact # š Redacts API key');\n console.log(' memory query research --namespace sparc');\n console.log();\n console.log(' # ReasoningBank mode (AI-powered, opt-in)');\n console.log(' memory init --reasoningbank # One-time setup');\n console.log(' memory store api_pattern \"Always use env vars\" --reasoningbank');\n console.log(' memory query \"API configuration\" --reasoningbank # Semantic search!');\n console.log(' memory status --reasoningbank # Show AI metrics');\n console.log();\n console.log(' # Auto-detect mode (smart selection)');\n console.log(' memory query config --auto # Uses ReasoningBank if available');\n console.log();\n console.log(' # Mode management');\n console.log(' memory detect # Show available modes');\n console.log(' memory mode # Show current configuration');\n console.log();\n console.log('š” Tips:');\n console.log(' ⢠AUTO MODE (default): Automatically uses best available storage');\n console.log(' ⢠ReasoningBank: AI-powered semantic search (learns from patterns)');\n console.log(' ⢠JSON fallback: Always available, fast, simple key-value storage');\n console.log(' ⢠Initialize ReasoningBank once: \"memory init --reasoningbank\"');\n console.log(' ⢠Always use --redact when storing API keys or secrets!');\n}\n"],"names":["printSuccess","printError","printWarning","printInfo","promises","fs","KeyRedactor","exec","promisify","execAsync","memoryCommand","subArgs","flags","memorySubcommand","memoryStore","namespace","ns","getNamespaceFromArgs","enableRedaction","redact","includes","mode","detectMemoryMode","loadMemory","content","readFile","JSON","parse","saveMemory","data","mkdir","recursive","writeFile","stringify","handleReasoningBankCommand","handleModeCommand","storeMemory","queryMemory","showMemoryStats","exportMemory","importMemory","clearMemory","listNamespaces","showMemoryHelp","key","value","slice","join","redactedValue","securityWarnings","validation","validate","safe","warnings","forEach","warning","console","log","filter","e","push","timestamp","Date","now","redacted","length","TextEncoder","encode","err","message","search","results","entries","Object","entry","sort","a","b","displayValue","substring","toLocaleString","totalEntries","namespaceStats","keys","toFixed","count","filename","exportData","values","importContent","importData","existingData","totalImported","existingKeys","Set","map","newEntries","has","nsFromArgs","entryCount","namespaces","namespaceIndex","indexOf","nsIndex","reasoningbank","rb","auto","initialized","isReasoningBankInitialized","basic","dbPath","access","command","initializeReasoningBank","queryMemories","listMemories","getStatus","checkReasoningBankTables","migrateReasoningBank","process","env","CLAUDE_FLOW_DB_PATH","tableCheck","exists","missingTables","migrationResult","success","addedTables","error","handleReasoningBankStore","handleReasoningBankQuery","handleReasoningBankList","handleReasoningBankStatus","cmd","stdout","timeout","getArgValue","memoryId","agent","domain","limit","confidence","usage_count","score","created_at","parseInt","stats","total_memories","avg_confidence","total_usage","total_embeddings","total_trajectories","buildReasoningBankCommand","parts","commandMap","store","query","list","status","consolidate","demo","test","benchmark","args","arg","startsWith","detectModes","showCurrentMode","migrateMemory","basicAvailable","checkBasicMode","rbAvailable","memoryDir","rbInitialized","targetMode","to","flag","index"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,EAAEC,SAAS,QAAQ,cAAc;AAChF,SAASC,YAAYC,EAAE,QAAQ,KAAK;AAGpC,SAASC,WAAW,QAAQ,8BAA8B;AAC1D,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AAEjC,MAAMC,YAAYD,UAAUD;AAE5B,OAAO,eAAeG,cAAcC,OAAO,EAAEC,KAAK;IAChD,MAAMC,mBAAmBF,OAAO,CAAC,EAAE;IACnC,MAAMG,cAAc;IAGpB,MAAMC,YAAYH,OAAOG,aAAaH,OAAOI,MAAMC,qBAAqBN,YAAY;IAGpF,MAAMO,kBAAkBN,OAAOO,UAAUR,QAAQS,QAAQ,CAAC,eAAeT,QAAQS,QAAQ,CAAC;IAG1F,MAAMC,OAAO,MAAMC,iBAAiBV,OAAOD;IAG3C,eAAeY;QACb,IAAI;YACF,MAAMC,UAAU,MAAMnB,GAAGoB,QAAQ,CAACX,aAAa;YAC/C,OAAOY,KAAKC,KAAK,CAACH;QACpB,EAAE,OAAM;YACN,OAAO,CAAC;QACV;IACF;IAGA,eAAeI,WAAWC,IAAI;QAC5B,MAAMxB,GAAGyB,KAAK,CAAC,YAAY;YAAEC,WAAW;QAAK;QAC7C,MAAM1B,GAAG2B,SAAS,CAAClB,aAAaY,KAAKO,SAAS,CAACJ,MAAM,MAAM,GAAG;IAChE;IAGA,IAAIR,SAAS,mBAAmB;QAAC;QAAQ;QAAU;QAAe;QAAQ;QAAQ;KAAY,CAACD,QAAQ,CAACP,mBAAmB;QACzH,OAAO,MAAMqB,2BAA2BrB,kBAAkBF,SAASC;I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AAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd"}
|
|
@@ -13,12 +13,90 @@ let metricsCache = {
|
|
|
13
13
|
system: [],
|
|
14
14
|
performance: {
|
|
15
15
|
startTime: Date.now(),
|
|
16
|
+
sessionId: `session-${Date.now()}`,
|
|
17
|
+
lastActivity: Date.now(),
|
|
18
|
+
sessionDuration: 0,
|
|
16
19
|
totalTasks: 0,
|
|
17
20
|
successfulTasks: 0,
|
|
18
21
|
failedTasks: 0,
|
|
19
22
|
totalAgents: 0,
|
|
20
23
|
activeAgents: 0,
|
|
21
|
-
neuralEvents: 0
|
|
24
|
+
neuralEvents: 0,
|
|
25
|
+
memoryMode: {
|
|
26
|
+
reasoningbankOperations: 0,
|
|
27
|
+
basicOperations: 0,
|
|
28
|
+
autoModeSelections: 0,
|
|
29
|
+
modeOverrides: 0,
|
|
30
|
+
currentMode: 'auto'
|
|
31
|
+
},
|
|
32
|
+
operations: {
|
|
33
|
+
store: {
|
|
34
|
+
count: 0,
|
|
35
|
+
totalDuration: 0,
|
|
36
|
+
errors: 0
|
|
37
|
+
},
|
|
38
|
+
retrieve: {
|
|
39
|
+
count: 0,
|
|
40
|
+
totalDuration: 0,
|
|
41
|
+
errors: 0
|
|
42
|
+
},
|
|
43
|
+
query: {
|
|
44
|
+
count: 0,
|
|
45
|
+
totalDuration: 0,
|
|
46
|
+
errors: 0
|
|
47
|
+
},
|
|
48
|
+
list: {
|
|
49
|
+
count: 0,
|
|
50
|
+
totalDuration: 0,
|
|
51
|
+
errors: 0
|
|
52
|
+
},
|
|
53
|
+
delete: {
|
|
54
|
+
count: 0,
|
|
55
|
+
totalDuration: 0,
|
|
56
|
+
errors: 0
|
|
57
|
+
},
|
|
58
|
+
search: {
|
|
59
|
+
count: 0,
|
|
60
|
+
totalDuration: 0,
|
|
61
|
+
errors: 0
|
|
62
|
+
},
|
|
63
|
+
init: {
|
|
64
|
+
count: 0,
|
|
65
|
+
totalDuration: 0,
|
|
66
|
+
errors: 0
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
performance: {
|
|
70
|
+
avgOperationDuration: 0,
|
|
71
|
+
minOperationDuration: null,
|
|
72
|
+
maxOperationDuration: null,
|
|
73
|
+
slowOperations: 0,
|
|
74
|
+
fastOperations: 0,
|
|
75
|
+
totalOperationTime: 0
|
|
76
|
+
},
|
|
77
|
+
storage: {
|
|
78
|
+
totalEntries: 0,
|
|
79
|
+
reasoningbankEntries: 0,
|
|
80
|
+
basicEntries: 0,
|
|
81
|
+
databaseSize: 0,
|
|
82
|
+
lastBackup: null,
|
|
83
|
+
growthRate: 0
|
|
84
|
+
},
|
|
85
|
+
errors: {
|
|
86
|
+
total: 0,
|
|
87
|
+
byType: {},
|
|
88
|
+
byOperation: {},
|
|
89
|
+
recent: []
|
|
90
|
+
},
|
|
91
|
+
reasoningbank: {
|
|
92
|
+
semanticSearches: 0,
|
|
93
|
+
sqlFallbacks: 0,
|
|
94
|
+
embeddingGenerated: 0,
|
|
95
|
+
consolidations: 0,
|
|
96
|
+
avgQueryTime: 0,
|
|
97
|
+
cacheHits: 0,
|
|
98
|
+
cacheMisses: 0
|
|
99
|
+
}
|
|
22
100
|
}
|
|
23
101
|
};
|
|
24
102
|
let systemMonitoringInterval = null;
|
|
@@ -120,6 +198,158 @@ export async function trackNeuralEvent(eventType, metadata = {}) {
|
|
|
120
198
|
metricsCache.performance.neuralEvents++;
|
|
121
199
|
await saveMetricsToDisk();
|
|
122
200
|
}
|
|
201
|
+
export async function trackMemoryOperation(operationType, mode, duration, success = true, errorType = null) {
|
|
202
|
+
metricsCache.performance.lastActivity = Date.now();
|
|
203
|
+
metricsCache.performance.sessionDuration = Date.now() - metricsCache.performance.startTime;
|
|
204
|
+
if (mode === 'reasoningbank') {
|
|
205
|
+
metricsCache.performance.memoryMode.reasoningbankOperations++;
|
|
206
|
+
} else if (mode === 'basic') {
|
|
207
|
+
metricsCache.performance.memoryMode.basicOperations++;
|
|
208
|
+
}
|
|
209
|
+
if (metricsCache.performance.operations[operationType]) {
|
|
210
|
+
const op = metricsCache.performance.operations[operationType];
|
|
211
|
+
op.count++;
|
|
212
|
+
op.totalDuration += duration;
|
|
213
|
+
if (!success) {
|
|
214
|
+
op.errors++;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const perf = metricsCache.performance.performance;
|
|
218
|
+
perf.totalOperationTime += duration;
|
|
219
|
+
const totalOps = Object.values(metricsCache.performance.operations).reduce((sum, op)=>sum + op.count, 0);
|
|
220
|
+
if (totalOps > 0) {
|
|
221
|
+
perf.avgOperationDuration = perf.totalOperationTime / totalOps;
|
|
222
|
+
}
|
|
223
|
+
if (perf.minOperationDuration === null || duration < perf.minOperationDuration) {
|
|
224
|
+
perf.minOperationDuration = duration;
|
|
225
|
+
}
|
|
226
|
+
if (perf.maxOperationDuration === null || duration > perf.maxOperationDuration) {
|
|
227
|
+
perf.maxOperationDuration = duration;
|
|
228
|
+
}
|
|
229
|
+
if (duration > 5000) {
|
|
230
|
+
perf.slowOperations++;
|
|
231
|
+
} else if (duration < 100) {
|
|
232
|
+
perf.fastOperations++;
|
|
233
|
+
}
|
|
234
|
+
if (!success && errorType) {
|
|
235
|
+
metricsCache.performance.errors.total++;
|
|
236
|
+
if (!metricsCache.performance.errors.byType[errorType]) {
|
|
237
|
+
metricsCache.performance.errors.byType[errorType] = 0;
|
|
238
|
+
}
|
|
239
|
+
metricsCache.performance.errors.byType[errorType]++;
|
|
240
|
+
if (!metricsCache.performance.errors.byOperation[operationType]) {
|
|
241
|
+
metricsCache.performance.errors.byOperation[operationType] = 0;
|
|
242
|
+
}
|
|
243
|
+
metricsCache.performance.errors.byOperation[operationType]++;
|
|
244
|
+
metricsCache.performance.errors.recent.push({
|
|
245
|
+
operation: operationType,
|
|
246
|
+
type: errorType,
|
|
247
|
+
timestamp: Date.now(),
|
|
248
|
+
mode
|
|
249
|
+
});
|
|
250
|
+
if (metricsCache.performance.errors.recent.length > 20) {
|
|
251
|
+
metricsCache.performance.errors.recent = metricsCache.performance.errors.recent.slice(-20);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
await saveMetricsToDisk();
|
|
255
|
+
}
|
|
256
|
+
export async function trackModeSelection(selectedMode, wasAutomatic = true) {
|
|
257
|
+
metricsCache.performance.memoryMode.currentMode = selectedMode;
|
|
258
|
+
if (wasAutomatic) {
|
|
259
|
+
metricsCache.performance.memoryMode.autoModeSelections++;
|
|
260
|
+
} else {
|
|
261
|
+
metricsCache.performance.memoryMode.modeOverrides++;
|
|
262
|
+
}
|
|
263
|
+
await saveMetricsToDisk();
|
|
264
|
+
}
|
|
265
|
+
export async function trackReasoningBankOperation(operationType, duration, metadata = {}) {
|
|
266
|
+
const rb = metricsCache.performance.reasoningbank;
|
|
267
|
+
switch(operationType){
|
|
268
|
+
case 'semantic_search':
|
|
269
|
+
rb.semanticSearches++;
|
|
270
|
+
break;
|
|
271
|
+
case 'sql_fallback':
|
|
272
|
+
rb.sqlFallbacks++;
|
|
273
|
+
break;
|
|
274
|
+
case 'embedding_generated':
|
|
275
|
+
rb.embeddingGenerated++;
|
|
276
|
+
break;
|
|
277
|
+
case 'consolidation':
|
|
278
|
+
rb.consolidations++;
|
|
279
|
+
break;
|
|
280
|
+
case 'cache_hit':
|
|
281
|
+
rb.cacheHits++;
|
|
282
|
+
break;
|
|
283
|
+
case 'cache_miss':
|
|
284
|
+
rb.cacheMisses++;
|
|
285
|
+
break;
|
|
286
|
+
}
|
|
287
|
+
const totalQueries = rb.semanticSearches + rb.sqlFallbacks;
|
|
288
|
+
if (totalQueries > 0) {
|
|
289
|
+
rb.avgQueryTime = (rb.avgQueryTime * (totalQueries - 1) + duration) / totalQueries;
|
|
290
|
+
}
|
|
291
|
+
await saveMetricsToDisk();
|
|
292
|
+
}
|
|
293
|
+
export async function updateStorageStats(totalEntries, reasoningbankEntries, basicEntries, databaseSize = 0) {
|
|
294
|
+
const storage = metricsCache.performance.storage;
|
|
295
|
+
const previousTotal = storage.totalEntries;
|
|
296
|
+
storage.totalEntries = totalEntries;
|
|
297
|
+
storage.reasoningbankEntries = reasoningbankEntries;
|
|
298
|
+
storage.basicEntries = basicEntries;
|
|
299
|
+
storage.databaseSize = databaseSize;
|
|
300
|
+
if (previousTotal > 0) {
|
|
301
|
+
const sessionHours = metricsCache.performance.sessionDuration / (1000 * 60 * 60);
|
|
302
|
+
if (sessionHours > 0) {
|
|
303
|
+
storage.growthRate = (totalEntries - previousTotal) / sessionHours;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
await saveMetricsToDisk();
|
|
307
|
+
}
|
|
308
|
+
export async function getMemoryPerformanceSummary() {
|
|
309
|
+
const perf = metricsCache.performance;
|
|
310
|
+
const totalOps = Object.values(perf.operations).reduce((sum, op)=>sum + op.count, 0);
|
|
311
|
+
const totalErrors = Object.values(perf.operations).reduce((sum, op)=>sum + op.errors, 0);
|
|
312
|
+
return {
|
|
313
|
+
session: {
|
|
314
|
+
sessionId: perf.sessionId,
|
|
315
|
+
duration: perf.sessionDuration,
|
|
316
|
+
startTime: new Date(perf.startTime).toISOString(),
|
|
317
|
+
lastActivity: new Date(perf.lastActivity).toISOString()
|
|
318
|
+
},
|
|
319
|
+
mode: {
|
|
320
|
+
current: perf.memoryMode.currentMode,
|
|
321
|
+
reasoningbankUsage: perf.memoryMode.reasoningbankOperations,
|
|
322
|
+
basicUsage: perf.memoryMode.basicOperations,
|
|
323
|
+
autoSelections: perf.memoryMode.autoModeSelections,
|
|
324
|
+
manualOverrides: perf.memoryMode.modeOverrides
|
|
325
|
+
},
|
|
326
|
+
operations: {
|
|
327
|
+
total: totalOps,
|
|
328
|
+
breakdown: perf.operations,
|
|
329
|
+
errors: totalErrors,
|
|
330
|
+
errorRate: totalOps > 0 ? totalErrors / totalOps * 100 : 0
|
|
331
|
+
},
|
|
332
|
+
performance: {
|
|
333
|
+
avgDuration: perf.performance.avgOperationDuration,
|
|
334
|
+
minDuration: perf.performance.minOperationDuration,
|
|
335
|
+
maxDuration: perf.performance.maxOperationDuration,
|
|
336
|
+
slowOps: perf.performance.slowOperations,
|
|
337
|
+
fastOps: perf.performance.fastOperations
|
|
338
|
+
},
|
|
339
|
+
storage: perf.storage,
|
|
340
|
+
reasoningbank: {
|
|
341
|
+
...perf.reasoningbank,
|
|
342
|
+
fallbackRate: perf.reasoningbank.semanticSearches > 0 ? perf.reasoningbank.sqlFallbacks / perf.reasoningbank.semanticSearches * 100 : 0,
|
|
343
|
+
cacheHitRate: perf.reasoningbank.cacheHits + perf.reasoningbank.cacheMisses > 0 ? perf.reasoningbank.cacheHits / (perf.reasoningbank.cacheHits + perf.reasoningbank.cacheMisses) * 100 : 0
|
|
344
|
+
},
|
|
345
|
+
errors: {
|
|
346
|
+
total: perf.errors.total,
|
|
347
|
+
byType: perf.errors.byType,
|
|
348
|
+
byOperation: perf.errors.byOperation,
|
|
349
|
+
recent: perf.errors.recent.slice(-5)
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
}
|
|
123
353
|
export async function getPerformanceReport(timeframe = '24h') {
|
|
124
354
|
const now = Date.now();
|
|
125
355
|
const timeframeMs = parseTimeframe(timeframe);
|