claude-flow 2.7.0-alpha ā 2.7.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/claude-flow +1 -1
- package/dist/src/cli/help-formatter.js +5 -0
- package/dist/src/cli/simple-commands/config.js +115 -257
- package/dist/src/cli/simple-commands/config.js.map +1 -1
- package/dist/src/cli/simple-commands/memory.js +120 -13
- package/dist/src/cli/simple-commands/memory.js.map +1 -1
- package/dist/src/reasoningbank/reasoningbank-adapter.js +144 -0
- package/dist/src/reasoningbank/reasoningbank-adapter.js.map +1 -0
- package/dist/src/utils/key-redactor.js.map +1 -1
- package/dist/src/utils/metrics-reader.js +39 -37
- package/dist/src/utils/metrics-reader.js.map +1 -1
- package/docs/REASONINGBANK-INTEGRATION-STATUS.md +179 -0
- package/package.json +1 -1
- package/src/cli/simple-commands/memory.js +148 -14
- package/src/reasoningbank/reasoningbank-adapter.js +191 -0
|
@@ -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 // Special handling for 'init' command\n if (command === 'init') {\n if (initialized) {\n printWarning('ā ļø ReasoningBank already initialized');\n console.log('Database: .swarm/memory.db');\n console.log('\\nTo reinitialize, delete .swarm/memory.db first');\n return;\n }\n\n printInfo('š§ Initializing ReasoningBank...');\n console.log('This will create: .swarm/memory.db\\n');\n\n try {\n const { stdout, stderr } = await execAsync('npx agentic-flow reasoningbank init', {\n timeout: 30000,\n });\n\n if (stdout) console.log(stdout);\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 if (error.stderr) {\n console.error('Details:', error.stderr);\n }\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 // Delegate to agentic-flow reasoningbank commands\n printInfo(`š§ Using ReasoningBank mode...`);\n\n try {\n const cmd = buildReasoningBankCommand(command, subArgs, flags);\n const { stdout, stderr } = await execAsync(cmd, { timeout: 30000 });\n\n if (stdout) console.log(stdout);\n if (stderr && !stderr.includes('Warning')) console.error(stderr);\n } catch (error) {\n printError(`ā ReasoningBank command failed`);\n console.error(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 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","stdout","stderr","timeout","error","cmd","buildReasoningBankCommand","parts","commandMap","store","query","list","status","consolidate","demo","test","benchmark","args","arg","startsWith","detectModes","showCurrentMode","migrateMemory","basicAvailable","checkBasicMode","rbAvailable","memoryDir","rbInitialized","targetMode","to","getArgValue","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,CAA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AQC,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;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;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 // 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 } = await import('../../reasoningbank/reasoningbank-adapter.js');\n\n // Special handling for 'init' command\n if (command === 'init') {\n if (initialized) {\n printWarning('ā ļø ReasoningBank already initialized');\n console.log('Database: .swarm/memory.db');\n console.log('\\nTo reinitialize, delete .swarm/memory.db first');\n return;\n }\n\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","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,Q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AAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd"}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { db, initialize, retrieveMemories, computeEmbedding, loadConfig } from 'agentic-flow/dist/reasoningbank/index.js';
|
|
2
|
+
import { v4 as uuidv4 } from 'uuid';
|
|
3
|
+
export async function initializeReasoningBank() {
|
|
4
|
+
process.env.CLAUDE_FLOW_DB_PATH = '.swarm/memory.db';
|
|
5
|
+
await initialize();
|
|
6
|
+
return true;
|
|
7
|
+
}
|
|
8
|
+
export async function storeMemory(key, value, options = {}) {
|
|
9
|
+
const memoryId = `mem_${uuidv4()}`;
|
|
10
|
+
const memory = {
|
|
11
|
+
id: memoryId,
|
|
12
|
+
type: options.type || 'fact',
|
|
13
|
+
pattern_data: JSON.stringify({
|
|
14
|
+
key,
|
|
15
|
+
value,
|
|
16
|
+
namespace: options.namespace || 'default',
|
|
17
|
+
agent: options.agent || 'memory-agent',
|
|
18
|
+
domain: options.domain || 'general'
|
|
19
|
+
}),
|
|
20
|
+
confidence: options.confidence || 0.8,
|
|
21
|
+
usage_count: 0,
|
|
22
|
+
created_at: new Date().toISOString()
|
|
23
|
+
};
|
|
24
|
+
db.upsertMemory(memory);
|
|
25
|
+
try {
|
|
26
|
+
const config = loadConfig();
|
|
27
|
+
const embeddingModel = config.embeddings.provider || 'claude';
|
|
28
|
+
const embedding = await computeEmbedding(`${key}: ${value}`);
|
|
29
|
+
const vectorArray = new Float32Array(embedding);
|
|
30
|
+
db.upsertEmbedding({
|
|
31
|
+
memory_id: memoryId,
|
|
32
|
+
vector: vectorArray,
|
|
33
|
+
model: embeddingModel,
|
|
34
|
+
dims: vectorArray.length,
|
|
35
|
+
created_at: new Date().toISOString()
|
|
36
|
+
});
|
|
37
|
+
} catch (error) {
|
|
38
|
+
console.warn('[ReasoningBank] Warning: Could not compute embedding:', error.message);
|
|
39
|
+
}
|
|
40
|
+
return memoryId;
|
|
41
|
+
}
|
|
42
|
+
export async function queryMemories(searchQuery, options = {}) {
|
|
43
|
+
try {
|
|
44
|
+
const memories = await retrieveMemories(searchQuery, {
|
|
45
|
+
domain: options.domain || 'general',
|
|
46
|
+
agent: options.agent || 'memory-agent',
|
|
47
|
+
k: options.limit || 10
|
|
48
|
+
});
|
|
49
|
+
return memories.map((mem)=>{
|
|
50
|
+
try {
|
|
51
|
+
const data = JSON.parse(mem.pattern_data);
|
|
52
|
+
return {
|
|
53
|
+
id: mem.id,
|
|
54
|
+
key: data.key,
|
|
55
|
+
value: data.value,
|
|
56
|
+
namespace: data.namespace,
|
|
57
|
+
confidence: mem.confidence,
|
|
58
|
+
usage_count: mem.usage_count,
|
|
59
|
+
created_at: mem.created_at,
|
|
60
|
+
score: mem.score || 0
|
|
61
|
+
};
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}).filter(Boolean);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
console.warn('[ReasoningBank] Semantic search failed, using simple query:', error.message);
|
|
68
|
+
const dbInstance = db.getDb();
|
|
69
|
+
const rows = dbInstance.prepare(`
|
|
70
|
+
SELECT * FROM patterns
|
|
71
|
+
WHERE pattern_data LIKE ?
|
|
72
|
+
ORDER BY confidence DESC, usage_count DESC
|
|
73
|
+
LIMIT ?
|
|
74
|
+
`).all(`%${searchQuery}%`, options.limit || 10);
|
|
75
|
+
return rows.map((row)=>{
|
|
76
|
+
try {
|
|
77
|
+
const data = JSON.parse(row.pattern_data);
|
|
78
|
+
return {
|
|
79
|
+
id: row.id,
|
|
80
|
+
key: data.key,
|
|
81
|
+
value: data.value,
|
|
82
|
+
namespace: data.namespace,
|
|
83
|
+
confidence: row.confidence,
|
|
84
|
+
usage_count: row.usage_count,
|
|
85
|
+
created_at: row.created_at
|
|
86
|
+
};
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}).filter(Boolean);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export async function listMemories(options = {}) {
|
|
94
|
+
const dbInstance = db.getDb();
|
|
95
|
+
const limit = options.limit || 10;
|
|
96
|
+
const sortBy = options.sort || 'created_at';
|
|
97
|
+
const sortOrder = options.order || 'DESC';
|
|
98
|
+
const rows = dbInstance.prepare(`
|
|
99
|
+
SELECT * FROM patterns
|
|
100
|
+
ORDER BY ${sortBy} ${sortOrder}
|
|
101
|
+
LIMIT ?
|
|
102
|
+
`).all(limit);
|
|
103
|
+
return rows.map((row)=>{
|
|
104
|
+
try {
|
|
105
|
+
const data = JSON.parse(row.pattern_data);
|
|
106
|
+
return {
|
|
107
|
+
id: row.id,
|
|
108
|
+
key: data.key,
|
|
109
|
+
value: data.value,
|
|
110
|
+
namespace: data.namespace,
|
|
111
|
+
confidence: row.confidence,
|
|
112
|
+
usage_count: row.usage_count,
|
|
113
|
+
created_at: row.created_at
|
|
114
|
+
};
|
|
115
|
+
} catch {
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
}).filter(Boolean);
|
|
119
|
+
}
|
|
120
|
+
export async function getStatus() {
|
|
121
|
+
const dbInstance = db.getDb();
|
|
122
|
+
const stats = dbInstance.prepare(`
|
|
123
|
+
SELECT
|
|
124
|
+
COUNT(*) as total_memories,
|
|
125
|
+
AVG(confidence) as avg_confidence,
|
|
126
|
+
SUM(usage_count) as total_usage
|
|
127
|
+
FROM patterns
|
|
128
|
+
`).get();
|
|
129
|
+
const embeddingCount = dbInstance.prepare(`
|
|
130
|
+
SELECT COUNT(*) as count FROM pattern_embeddings
|
|
131
|
+
`).get();
|
|
132
|
+
const trajectoryCount = dbInstance.prepare(`
|
|
133
|
+
SELECT COUNT(*) as count FROM task_trajectories
|
|
134
|
+
`).get();
|
|
135
|
+
return {
|
|
136
|
+
total_memories: stats.total_memories || 0,
|
|
137
|
+
avg_confidence: stats.avg_confidence || 0,
|
|
138
|
+
total_usage: stats.total_usage || 0,
|
|
139
|
+
total_embeddings: embeddingCount.count || 0,
|
|
140
|
+
total_trajectories: trajectoryCount.count || 0
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
//# sourceMappingURL=reasoningbank-adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/reasoningbank/reasoningbank-adapter.js"],"sourcesContent":["/**\n * ReasoningBank Adapter for Claude-Flow\n *\n * Wraps agentic-flow's ReasoningBank SDK for use in claude-flow memory commands\n */\n\nimport { db, initialize, retrieveMemories, computeEmbedding, loadConfig } from 'agentic-flow/dist/reasoningbank/index.js';\nimport { v4 as uuidv4 } from 'uuid';\n\n/**\n * Initialize ReasoningBank database\n */\nexport async function initializeReasoningBank() {\n // Set database path\n process.env.CLAUDE_FLOW_DB_PATH = '.swarm/memory.db';\n\n await initialize();\n return true;\n}\n\n/**\n * Store a memory in ReasoningBank\n */\nexport async function storeMemory(key, value, options = {}) {\n const memoryId = `mem_${uuidv4()}`;\n\n const memory = {\n id: memoryId,\n type: options.type || 'fact',\n pattern_data: JSON.stringify({\n key,\n value,\n namespace: options.namespace || 'default',\n agent: options.agent || 'memory-agent',\n domain: options.domain || 'general',\n }),\n confidence: options.confidence || 0.8,\n usage_count: 0,\n created_at: new Date().toISOString(),\n };\n\n // Store memory\n db.upsertMemory(memory);\n\n // Compute and store embedding for semantic search\n try {\n const config = loadConfig();\n const embeddingModel = config.embeddings.provider || 'claude';\n\n const embedding = await computeEmbedding(`${key}: ${value}`);\n const vectorArray = new Float32Array(embedding);\n\n db.upsertEmbedding({\n memory_id: memoryId,\n vector: vectorArray,\n model: embeddingModel, // Dynamic model from config\n dims: vectorArray.length, // Required: embedding dimensions\n created_at: new Date().toISOString(),\n });\n } catch (error) {\n console.warn('[ReasoningBank] Warning: Could not compute embedding:', error.message);\n // Continue without embedding - memory is still stored\n }\n\n return memoryId;\n}\n\n/**\n * Query memories from ReasoningBank\n */\nexport async function queryMemories(searchQuery, options = {}) {\n try {\n // Use ReasoningBank's semantic retrieval\n const memories = await retrieveMemories(searchQuery, {\n domain: options.domain || 'general',\n agent: options.agent || 'memory-agent',\n k: options.limit || 10,\n });\n\n return memories.map(mem => {\n try {\n const data = JSON.parse(mem.pattern_data);\n return {\n id: mem.id,\n key: data.key,\n value: data.value,\n namespace: data.namespace,\n confidence: mem.confidence,\n usage_count: mem.usage_count,\n created_at: mem.created_at,\n score: mem.score || 0,\n };\n } catch {\n return null;\n }\n }).filter(Boolean);\n } catch (error) {\n // Fallback to simple query if semantic search fails\n console.warn('[ReasoningBank] Semantic search failed, using simple query:', error.message);\n\n const dbInstance = db.getDb();\n const rows = dbInstance.prepare(`\n SELECT * FROM patterns\n WHERE pattern_data LIKE ?\n ORDER BY confidence DESC, usage_count DESC\n LIMIT ?\n `).all(`%${searchQuery}%`, options.limit || 10);\n\n return rows.map(row => {\n try {\n const data = JSON.parse(row.pattern_data);\n return {\n id: row.id,\n key: data.key,\n value: data.value,\n namespace: data.namespace,\n confidence: row.confidence,\n usage_count: row.usage_count,\n created_at: row.created_at,\n };\n } catch {\n return null;\n }\n }).filter(Boolean);\n }\n}\n\n/**\n * List all memories\n */\nexport async function listMemories(options = {}) {\n const dbInstance = db.getDb();\n\n const limit = options.limit || 10;\n const sortBy = options.sort || 'created_at';\n const sortOrder = options.order || 'DESC';\n\n const rows = dbInstance.prepare(`\n SELECT * FROM patterns\n ORDER BY ${sortBy} ${sortOrder}\n LIMIT ?\n `).all(limit);\n\n return rows.map(row => {\n try {\n const data = JSON.parse(row.pattern_data);\n return {\n id: row.id,\n key: data.key,\n value: data.value,\n namespace: data.namespace,\n confidence: row.confidence,\n usage_count: row.usage_count,\n created_at: row.created_at,\n };\n } catch {\n return null;\n }\n }).filter(Boolean);\n}\n\n/**\n * Get ReasoningBank statistics\n */\nexport async function getStatus() {\n const dbInstance = db.getDb();\n\n const stats = dbInstance.prepare(`\n SELECT\n COUNT(*) as total_memories,\n AVG(confidence) as avg_confidence,\n SUM(usage_count) as total_usage\n FROM patterns\n `).get();\n\n const embeddingCount = dbInstance.prepare(`\n SELECT COUNT(*) as count FROM pattern_embeddings\n `).get();\n\n const trajectoryCount = dbInstance.prepare(`\n SELECT COUNT(*) as count FROM task_trajectories\n `).get();\n\n return {\n total_memories: stats.total_memories || 0,\n avg_confidence: stats.avg_confidence || 0,\n total_usage: stats.total_usage || 0,\n total_embeddings: embeddingCount.count || 0,\n total_trajectories: trajectoryCount.count || 0,\n };\n}\n"],"names":["db","initialize","retrieveMemories","computeEmbedding","loadConfig","v4","uuidv4","initializeReasoningBank","process","env","CLAUDE_FLOW_DB_PATH","storeMemory","key","value","options","memoryId","memory","id","type","pattern_data","JSON","stringify","namespace","agent","domain","confidence","usage_count","created_at","Date","toISOString","upsertMemory","config","embeddingModel","embeddings","provider","embedding","vectorArray","Float32Array","upsertEmbedding","memory_id","vector","model","dims","length","error","console","warn","message","queryMemories","searchQuery","memories","k","limit","map","mem","data","parse","score","filter","Boolean","dbInstance","getDb","rows","prepare","all","row","listMemories","sortBy","sort","sortOrder","order","getStatus","stats","get","embeddingCount","trajectoryCount","total_memories","avg_confidence","total_usage","total_embeddings","count","total_trajectories"],"mappings":"AAMA,SAAUA,EAAE,EAAEC,UAAU,EAAEC,gBAAgB,EAAEC,gBAAgB,EAAEC,UAAU,QAAQ,2CAA2C;AAC3H,SAASC,MAAMC,MAAM,QAAQ,OAAO;AAKpC,OAAO,eAAeC;IAEpBC,QAAQC,GAAG,CAACC,mBAAmB,GAAG;IAElC,MAAMT;IACN,OAAO;AACT;AAKA,OAAO,eAAeU,YAAYC,GAAG,EAAEC,KAAK,EAAEC,UAAU,CAAC,CAAC;IACxD,MAAMC,WAAW,CAAC,IAAI,EAAET,UAAU;IAElC,MAAMU,SAAS;QACbC,IAAIF;QACJG,MAAMJ,QAAQI,IAAI,IAAI;QACtBC,cAAcC,KAAKC,SAAS,CAAC;YAC3BT;YACAC;YACAS,WAAWR,QAAQQ,SAAS,IAAI;YAChCC,OAAOT,QAAQS,KAAK,I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0C,KAAK1C,KAAK;gBACjBS,WAAWiC,KAAKjC,SAAS;gBACzBG,YAAYwC,IAAIxC,UAAU;gBAC1BC,aAAauC,IAAIvC,WAAW;gBAC5BC,YAAYsC,IAAItC,UAAU;YAC5B;QACF,EAAE,OAAM;YACN,OAAO;QACT;IACF,GAAG+B,MAAM,CAACC;AACZ;AAKA,OAAO,eAAeY;IACpB,MAAMX,aAAa5D,GAAG6D,KAAK;IAE3B,MAAMW,QAAQZ,WAAWG,OAAO,CAAC,CAAC;;;;;;EAMlC,CAAC,EAAEU,GAAG;IAEN,MAAMC,iBAAiBd,WAAWG,OAAO,CAAC,CAAC;;EAE3C,CAAC,EAAEU,GAAG;IAEN,MAAME,kBAAkBf,WAAWG,OAAO,CAAC,CAAC;;EAE5C,CAAC,EAAEU,GAAG;IAEN,OAAO;QACLG,gBAAgBJ,MAAMI,cAAc,IAAI;QACxCC,gBAAgBL,MAAMK,cAAc,IAAI;QACxCC,aAAaN,MAAMM,WAAW,IAAI;QAClCC,kBAAkBL,eAAeM,KAAK,IAAI;QAC1CC,oBAAoBN,gBAAgBK,KAAK,IAAI;IAC/C;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/key-redactor.
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/key-redactor.ts"],"sourcesContent":["/**\n * API Key Redaction Utility\n * Prevents sensitive data from leaking into logs, memory, or git commits\n */\n\nexport interface RedactionConfig {\n patterns: RegExp[];\n replacement: string;\n maskLength: number;\n}\n\nexport class KeyRedactor {\n private static readonly API_KEY_PATTERNS = [\n // Anthropic API keys\n /sk-ant-[a-zA-Z0-9_-]{95,}/gi,\n\n // OpenRouter API keys\n /sk-or-[a-zA-Z0-9_-]{32,}/gi,\n\n // Google/Gemini API keys\n /AIza[a-zA-Z0-9_-]{35}/gi,\n\n // Generic API keys\n /[a-zA-Z0-9_-]{20,}API[a-zA-Z0-9_-]{20,}/gi,\n\n // Bearer tokens\n /Bearer\\s+[a-zA-Z0-9_\\-\\.]{20,}/gi,\n\n // Environment variable format\n /([A-Z_]+_API_KEY|[A-Z_]+_TOKEN|[A-Z_]+_SECRET)=[\"']?([^\"'\\s]+)[\"']?/gi,\n\n // Supabase keys\n /eyJ[a-zA-Z0-9_-]*\\.eyJ[a-zA-Z0-9_-]*\\.[a-zA-Z0-9_-]*/gi,\n ];\n\n private static readonly SENSITIVE_FIELDS = [\n 'apiKey',\n 'api_key',\n 'token',\n 'secret',\n 'password',\n 'private_key',\n 'privateKey',\n 'accessToken',\n 'access_token',\n 'refreshToken',\n 'refresh_token',\n ];\n\n /**\n * Redact API keys and sensitive data from text\n */\n static redact(text: string, showPrefix = true): string {\n if (!text) return text;\n\n let redacted = text;\n\n // Redact using patterns\n this.API_KEY_PATTERNS.forEach(pattern => {\n redacted = redacted.replace(pattern, (match) => {\n if (showPrefix && match.length > 8) {\n const prefix = match.substring(0, 8);\n return `${prefix}...[REDACTED]`;\n }\n return '[REDACTED_API_KEY]';\n });\n });\n\n return redacted;\n }\n\n /**\n * Redact sensitive fields in objects\n */\n static redactObject<T extends Record<string, any>>(obj: T, deep = true): T {\n if (!obj || typeof obj !== 'object') return obj;\n\n const redacted = { ...obj };\n\n Object.keys(redacted).forEach(key => {\n const lowerKey = key.toLowerCase();\n\n // Check if field name is sensitive\n const isSensitive = this.SENSITIVE_FIELDS.some(field =>\n lowerKey.includes(field)\n );\n\n if (isSensitive && typeof redacted[key] === 'string') {\n const value = redacted[key] as string;\n if (value && value.length > 8) {\n redacted[key] = `${value.substring(0, 4)}...[REDACTED]` as any;\n } else {\n redacted[key] = '[REDACTED]' as any;\n }\n } else if (deep && typeof redacted[key] === 'object' && redacted[key] !== null) {\n redacted[key] = this.redactObject(redacted[key], deep);\n } else if (typeof redacted[key] === 'string') {\n // Redact any API keys in string values\n redacted[key] = this.redact(redacted[key]) as any;\n }\n });\n\n return redacted;\n }\n\n /**\n * Sanitize text for safe logging\n */\n static sanitize(text: string): string {\n return this.redact(text, true);\n }\n\n /**\n * Sanitize command arguments\n */\n static sanitizeArgs(args: string[]): string[] {\n return args.map(arg => {\n // Check if arg is a flag value pair\n if (arg.includes('key') || arg.includes('token') || arg.includes('secret')) {\n return this.redact(arg);\n }\n return arg;\n });\n }\n\n /**\n * Check if text contains unredacted sensitive data\n */\n static containsSensitiveData(text: string): boolean {\n return this.API_KEY_PATTERNS.some(pattern => pattern.test(text));\n }\n\n /**\n * Validate that text is safe for logging/storage\n */\n static validate(text: string): { safe: boolean; warnings: string[] } {\n const warnings: string[] = [];\n\n this.API_KEY_PATTERNS.forEach((pattern, index) => {\n if (pattern.test(text)) {\n warnings.push(`Potential API key detected (pattern ${index + 1})`);\n }\n });\n\n return {\n safe: warnings.length === 0,\n warnings,\n };\n }\n\n /**\n * Redact environment variables\n */\n static redactEnv(env: Record<string, string | undefined>): Record<string, string> {\n const redacted: Record<string, string> = {};\n\n Object.keys(env).forEach(key => {\n const value = env[key];\n if (!value) {\n redacted[key] = '';\n return;\n }\n\n const lowerKey = key.toLowerCase();\n const isSensitive = lowerKey.includes('key') ||\n lowerKey.includes('token') ||\n lowerKey.includes('secret') ||\n lowerKey.includes('password');\n\n if (isSensitive) {\n redacted[key] = value.length > 8\n ? `${value.substring(0, 4)}...[REDACTED]`\n : '[REDACTED]';\n } else {\n redacted[key] = value;\n }\n });\n\n return redacted;\n }\n}\n\n// Export singleton instance\nexport const redactor = KeyRedactor;\n"],"names":["KeyRedactor","API_KEY_PATTERNS","SENSITIVE_FIELDS","redact","text","showPrefix","redacted","forEach","pattern","replace","match","length","prefix","substring","redactObject","obj","deep","Object","keys","key","lowerKey","toLowerCase","isSensitive","some","field","includes","value","sanitize","sanitizeArgs","args","map","arg","containsSensitiveData","test","validate","warnings","index","push","safe","redactEnv","env","redactor"],"mappings":"AAWA,OAAO,MAAMA;IACX,OAAwBC,mBAAmB;QAEzC;QAGA;QAGA;QAGA;QAGA;QAGA;QAGA;KACD,CAAC;IAEF,OAAwBC,mBAAmB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MC,cAAcF,SAASK,QAAQ,CAAC,UACnBL,SAASK,QAAQ,CAAC,YAClBL,SAASK,QAAQ,CAAC,aAClBL,SAASK,QAAQ,CAAC;YAErC,IAAIH,aAAa;gBACfhB,QAAQ,CAACa,IAAI,GAAGO,MAAMf,MAAM,GAAG,IAC3B,GAAGe,MAAMb,SAAS,CAAC,GAAG,GAAG,aAAa,CAAC,GACvC;YACN,OAAO;gBACLP,QAAQ,CAACa,IAAI,GAAGO;YAClB;QACF;QAEA,OAAOpB;IACT;AACF;AAGA,OAAO,MAAMmC,WAAWzC,YAAY"}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import { promises as fs } from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
3
|
import { exec } from 'child_process';
|
|
4
4
|
import { promisify } from 'util';
|
|
5
5
|
const execAsync = promisify(exec);
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
let MetricsReader = class MetricsReader {
|
|
7
|
+
constructor(){
|
|
8
|
+
this.metricsDir = '.claude-flow/metrics';
|
|
9
|
+
this.sessionsDir = '.claude-flow/sessions';
|
|
10
|
+
}
|
|
9
11
|
async getSystemMetrics() {
|
|
10
12
|
try {
|
|
11
13
|
const filePath = path.join(this.metricsDir, 'system-metrics.json');
|
|
@@ -16,6 +18,15 @@ export class MetricsReader {
|
|
|
16
18
|
return null;
|
|
17
19
|
}
|
|
18
20
|
}
|
|
21
|
+
async getTaskQueue() {
|
|
22
|
+
try {
|
|
23
|
+
const queueFile = '.claude-flow/tasks/queue.json';
|
|
24
|
+
const content = await fs.readFile(queueFile, 'utf8');
|
|
25
|
+
return JSON.parse(content);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
}
|
|
19
30
|
async getTaskMetrics() {
|
|
20
31
|
try {
|
|
21
32
|
const filePath = path.join(this.metricsDir, 'task-metrics.json');
|
|
@@ -36,30 +47,30 @@ export class MetricsReader {
|
|
|
36
47
|
}
|
|
37
48
|
async getActiveAgents() {
|
|
38
49
|
try {
|
|
39
|
-
const perfMetrics = await this.getPerformanceMetrics();
|
|
40
|
-
const sessionFiles = await this.getSessionFiles();
|
|
41
50
|
const agents = [];
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
if (
|
|
47
|
-
|
|
51
|
+
const agentsDir = '.claude-flow/agents';
|
|
52
|
+
try {
|
|
53
|
+
const agentFiles = await fs.readdir(agentsDir);
|
|
54
|
+
for (const file of agentFiles){
|
|
55
|
+
if (file.endsWith('.json')) {
|
|
56
|
+
try {
|
|
57
|
+
const content = await fs.readFile(path.join(agentsDir, file), 'utf8');
|
|
58
|
+
const agent = JSON.parse(content);
|
|
59
|
+
agents.push(agent);
|
|
60
|
+
} catch {}
|
|
48
61
|
}
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
if (agents.length === 0
|
|
52
|
-
const
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
lastActivity: Date.now() - i * 1000
|
|
62
|
-
});
|
|
62
|
+
}
|
|
63
|
+
} catch {}
|
|
64
|
+
if (agents.length === 0) {
|
|
65
|
+
const sessionFiles = await this.getSessionFiles();
|
|
66
|
+
for (const file of sessionFiles){
|
|
67
|
+
try {
|
|
68
|
+
const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');
|
|
69
|
+
const sessionData = JSON.parse(content);
|
|
70
|
+
if (sessionData.agents && Array.isArray(sessionData.agents)) {
|
|
71
|
+
agents.push(...sessionData.agents);
|
|
72
|
+
}
|
|
73
|
+
} catch {}
|
|
63
74
|
}
|
|
64
75
|
}
|
|
65
76
|
return agents;
|
|
@@ -135,7 +146,7 @@ export class MetricsReader {
|
|
|
135
146
|
}
|
|
136
147
|
async getMCPServerStatus() {
|
|
137
148
|
try {
|
|
138
|
-
const { stdout } = await execAsync('ps aux | grep -E "mcp
|
|
149
|
+
const { stdout } = await execAsync('ps aux | grep -E "mcp" | grep -v grep | wc -l');
|
|
139
150
|
const processCount = parseInt(stdout.trim(), 10);
|
|
140
151
|
const { stdout: orchestratorOut } = await execAsync('ps aux | grep -E "claude-flow start" | grep -v grep | wc -l');
|
|
141
152
|
const orchestratorRunning = parseInt(orchestratorOut.trim(), 10) > 0;
|
|
@@ -164,15 +175,6 @@ export class MetricsReader {
|
|
|
164
175
|
};
|
|
165
176
|
}
|
|
166
177
|
}
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
//# sourceMappingURL=metrics-reader.js.map processCount: 0,
|
|
170
|
-
orchestratorRunning: false,
|
|
171
|
-
port: null,
|
|
172
|
-
connections: 0
|
|
173
|
-
};
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
178
|
};
|
|
177
179
|
export { MetricsReader };
|
|
178
180
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/metrics-reader.ts"],"sourcesContent":["import * as fs from 'fs/promises';\nimport * as path from 'path';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\ninterface SystemMetrics {\n timestamp: number;\n memoryTotal: number;\n memoryUsed: number;\n memoryFree: number;\n memoryUsagePercent: number;\n memoryEfficiency: number;\n cpuCount: number;\n cpuLoad: number;\n platform: string;\n uptime: number;\n}\n\ninterface TaskMetric {\n id: string;\n type: string;\n success: boolean;\n duration: number;\n timestamp: number;\n metadata: Record<string, any>;\n}\n\ninterface PerformanceMetrics {\n startTime: number;\n totalTasks: number;\n successfulTasks: number;\n failedTasks: number;\n totalAgents: number;\n activeAgents: number;\n neuralEvents: number;\n}\n\ninterface Agent {\n id: string;\n name: string;\n type: string;\n status: 'active' | 'idle' | 'busy';\n activeTasks: number;\n lastActivity?: number;\n}\n\ninterface SessionData {\n id: string;\n startTime: number;\n endTime?: number;\n agents: Agent[];\n tasks: any[];\n status: 'active' | 'completed' | 'paused';\n}\n\ninterface MCPServerStatus {\n running: boolean;\n processCount: number;\n orchestratorRunning: boolean;\n port: number | null;\n connections: number;\n}\n\nexport class MetricsReader {\n private metricsDir = '.claude-flow/metrics';\n private sessionsDir = '.claude-flow/sessions';\n\n async getSystemMetrics(): Promise<SystemMetrics | null> {\n try {\n const filePath = path.join(this.metricsDir, 'system-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n const metrics: SystemMetrics[] = JSON.parse(content);\n \n // Return the most recent metric\n return metrics.length > 0 ? metrics[metrics.length - 1] : null;\n } catch (error) {\n return null;\n }\n }\n\n async getTaskMetrics(): Promise<TaskMetric[]> {\n try {\n const filePath = path.join(this.metricsDir, 'task-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return [];\n }\n }\n\n async getPerformanceMetrics(): Promise<PerformanceMetrics | null> {\n try {\n const filePath = path.join(this.metricsDir, 'performance.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getActiveAgents(): Promise<Agent[]> {\n try {\n // First check performance metrics for agent count\n const perfMetrics = await this.getPerformanceMetrics();\n \n // Also check session files for more detailed agent info\n const sessionFiles = await this.getSessionFiles();\n const agents: Agent[] = [];\n \n for (const file of sessionFiles) {\n try {\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');\n const sessionData = JSON.parse(content);\n \n if (sessionData.agents && Array.isArray(sessionData.agents)) {\n agents.push(...sessionData.agents);\n }\n } catch {\n // Skip invalid session files\n }\n }\n \n // If no agents found in sessions, create mock agents based on performance metrics\n if (agents.length === 0 && perfMetrics) {\n const activeCount = perfMetrics.activeAgents || 0;\n const totalCount = perfMetrics.totalAgents || 0;\n \n for (let i = 0; i < totalCount; i++) {\n agents.push({\n id: `agent-${i + 1}`,\n name: `Agent ${i + 1}`,\n type: i === 0 ? 'orchestrator' : 'worker',\n status: i < activeCount ? 'active' : 'idle',\n activeTasks: i < activeCount ? 1 : 0,\n lastActivity: Date.now() - (i * 1000)\n });\n }\n }\n \n return agents;\n } catch (error) {\n return [];\n }\n }\n\n async getSessionStatus(): Promise<SessionData | null> {\n try {\n const sessionFiles = await this.getSessionFiles();\n \n if (sessionFiles.length === 0) {\n return null;\n }\n \n // Get the most recent session\n const mostRecentFile = sessionFiles[sessionFiles.length - 1];\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', mostRecentFile), 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getRecentTasks(limit: number = 10): Promise<any[]> {\n try {\n const taskMetrics = await this.getTaskMetrics();\n \n // Sort by timestamp descending and take the limit\n return taskMetrics\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, limit)\n .map(task => ({\n id: task.id,\n type: task.type,\n status: task.success ? 'completed' : 'failed',\n startTime: task.timestamp - task.duration,\n endTime: task.timestamp,\n duration: task.duration\n }));\n } catch (error) {\n return [];\n }\n }\n\n async getOverallHealth(): Promise<'healthy' | 'warning' | 'error'> {\n try {\n const systemMetrics = await this.getSystemMetrics();\n const perfMetrics = await this.getPerformanceMetrics();\n \n if (!systemMetrics && !perfMetrics) {\n return 'error';\n }\n \n // Check memory usage\n if (systemMetrics && systemMetrics.memoryUsagePercent > 90) {\n return 'error';\n }\n \n if (systemMetrics && systemMetrics.memoryUsagePercent > 75) {\n return 'warning';\n }\n \n // Check CPU load\n if (systemMetrics && systemMetrics.cpuLoad > 0.8) {\n return 'warning';\n }\n \n // Check task failure rate\n if (perfMetrics && perfMetrics.totalTasks > 0) {\n const failureRate = perfMetrics.failedTasks / perfMetrics.totalTasks;\n if (failureRate > 0.5) {\n return 'error';\n }\n if (failureRate > 0.2) {\n return 'warning';\n }\n }\n \n return 'healthy';\n } catch (error) {\n return 'error';\n }\n }\n\n private async getSessionFiles(): Promise<string[]> {\n try {\n const files = await fs.readdir(path.join(this.sessionsDir, 'pair'));\n return files.filter(f => f.endsWith('.json')).sort();\n } catch (error) {\n return [];\n }\n }\n\n async getMCPServerStatus(): Promise<MCPServerStatus> {\n try {\n // Check if MCP server process is running\n const { stdout } = await execAsync('ps aux | grep -E \"mcp-server\\\\.js|claude-flow mcp start\" | grep -v grep | wc -l');\n const processCount = parseInt(stdout.trim(), 10);\n \n // Check for orchestrator running\n const { stdout: orchestratorOut } = await execAsync('ps aux | grep -E \"claude-flow start\" | grep -v grep | wc -l');\n const orchestratorRunning = parseInt(orchestratorOut.trim(), 10) > 0;\n \n // Determine status\n const isRunning = processCount > 0;\n \n // Try to get port from process (default is 3000)\n let port: number | null = 3000;\n try {\n const { stdout: portOut } = await execAsync('lsof -i :3000 2>/dev/null | grep LISTEN | wc -l');\n if (parseInt(portOut.trim(), 10) === 0) {\n // If port 3000 not listening, check other common ports\n port = null;\n }\n } catch {\n // lsof might not be available or port not in use\n }\n \n return {\n running: isRunning,\n processCount,\n orchestratorRunning,\n port,\n connections: processCount > 0 ? Math.max(1, processCount - 1) : 0 // Estimate connections\n };\n } catch (error) {\n // Fallback if commands fail\n return {\n running: false,\n processCount: 0,\n orchestratorRunning: false,\n port: null,\n connections: 0\n };\n }\n }\n}"],"names":["fs","path","exec","promisify","execAsync","MetricsReader","metricsDir","sessionsDir","getSystemMetrics","filePath","join","content","readFile","metrics","JSON","parse","length","error","getTaskMetrics","getPerformanceMetrics","getActiveAgents","perfMetrics","sessionFiles","getSessionFiles","agents","file","sessionData","Array","isArray","push","activeCount","activeAgents","totalCount","totalAgents","i","id","name","type","status","activeTasks","lastActivity","Date","now","getSessionStatus","mostRecentFile","getRecentTasks","limit","taskMetrics","sort","a","b","timestamp","slice","map","task","success","startTime","duration","endTime","getOverallHealth","systemMetrics","memoryUsagePercent","cpuLoad","totalTasks","failureRate","failedTasks","files","readdir","filter","f","endsWith","getMCPServerStatus","stdout","processCount","parseInt","trim","orchestratorOut","orchestratorRunning","isRunning","port","portOut","running","connections","Math","max"],"mappings":"AAAA,YAAYA,QA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AC,IAAI,CAACH,WAAW,EAAE;YAC3D,OAAO2D,MAAME,MAAM,CAACC,CAAAA,IAAKA,EAAEC,QAAQ,CAAC,UAAUtB,IAAI;QACpD,EAAE,OAAO/B,OAAO;YACd,OAAO,EAAE;QACX;IACF;IAEA,MAAMsD,qBAA+C;QACnD,IAAI;YAEF,MAAM,EAAEC,MAAM,EAAE,GAAG,MAAMpE,UAAU;YACnC,MAAMqE,eAAeC,SAASF,OAAOG,IAAI,IAAI;YAG7C,MAAM,EAAEH,QAAQI,eAAe,EAAE,GAAG,MAAMxE,UAAU;YACpD,MAAMyE,sBAAsBH,SAASE,gBAAgBD,IAAI,IAAI,MAAM;YAGnE,MAAMG,YAAYL,eAAe;YAGjC,IAAIM,OAAsB;YAC1B,IAAI;gBACF,MAAM,EAAEP,QAAQQ,OAAO,EAAE,GAAG,MAAM5E,UAAU;gBAC5C,IAAIsE,SAASM,QAAQL,IAAI,IAAI,QAAQ,GAAG;oBAEtCI,OAAO;gBACT;YACF,EAAE,OAAM,CAER;YAEA,OAAO;gBACLE,SAASH;gBACTL;gBACAI;gBACAE;gBACAG,aAAaT,eAAe,IAAIU,KAAKC,GAAG,CAAC,GAAGX,eAAe,KAAK;YAClE;QACF,EAAE,OAAOxD,OAAO;YAEd,OAAO;gBACLgE,SAAS;gBACTR,cAAc;gBACdI,qBAAqB;gBACrBE,MAAM;gBACNG,aAAa;YACf;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/metrics-reader.js"],"sourcesContent":["import { promises as fs } from 'fs';\nimport path from 'path';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nclass MetricsReader {\n constructor() {\n this.metricsDir = '.claude-flow/metrics';\n this.sessionsDir = '.claude-flow/sessions';\n }\n\n async getSystemMetrics() {\n try {\n const filePath = path.join(this.metricsDir, 'system-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n const metrics = JSON.parse(content);\n \n // Return the most recent metric\n return metrics.length > 0 ? metrics[metrics.length - 1] : null;\n } catch (error) {\n return null;\n }\n }\n\n async getTaskQueue() {\n try {\n const queueFile = '.claude-flow/tasks/queue.json';\n const content = await fs.readFile(queueFile, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return [];\n }\n }\n\n async getTaskMetrics() {\n try {\n const filePath = path.join(this.metricsDir, 'task-metrics.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return [];\n }\n }\n\n async getPerformanceMetrics() {\n try {\n const filePath = path.join(this.metricsDir, 'performance.json');\n const content = await fs.readFile(filePath, 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getActiveAgents() {\n try {\n const agents = [];\n \n // Check for agents in the .claude-flow/agents directory\n const agentsDir = '.claude-flow/agents';\n try {\n const agentFiles = await fs.readdir(agentsDir);\n for (const file of agentFiles) {\n if (file.endsWith('.json')) {\n try {\n const content = await fs.readFile(path.join(agentsDir, file), 'utf8');\n const agent = JSON.parse(content);\n agents.push(agent);\n } catch {\n // Skip invalid agent files\n }\n }\n }\n } catch {\n // Agents directory doesn't exist yet\n }\n \n // If no agents found in directory, check session files\n if (agents.length === 0) {\n const sessionFiles = await this.getSessionFiles();\n for (const file of sessionFiles) {\n try {\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', file), 'utf8');\n const sessionData = JSON.parse(content);\n \n if (sessionData.agents && Array.isArray(sessionData.agents)) {\n agents.push(...sessionData.agents);\n }\n } catch {\n // Skip invalid session files\n }\n }\n }\n \n return agents;\n } catch (error) {\n return [];\n }\n }\n\n async getSessionStatus() {\n try {\n const sessionFiles = await this.getSessionFiles();\n \n if (sessionFiles.length === 0) {\n return null;\n }\n \n // Get the most recent session\n const mostRecentFile = sessionFiles[sessionFiles.length - 1];\n const content = await fs.readFile(path.join(this.sessionsDir, 'pair', mostRecentFile), 'utf8');\n return JSON.parse(content);\n } catch (error) {\n return null;\n }\n }\n\n async getRecentTasks(limit = 10) {\n try {\n const taskMetrics = await this.getTaskMetrics();\n \n // Sort by timestamp descending and take the limit\n return taskMetrics\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, limit)\n .map(task => ({\n id: task.id,\n type: task.type,\n status: task.success ? 'completed' : 'failed',\n startTime: task.timestamp - task.duration,\n endTime: task.timestamp,\n duration: task.duration\n }));\n } catch (error) {\n return [];\n }\n }\n\n async getOverallHealth() {\n try {\n const systemMetrics = await this.getSystemMetrics();\n const perfMetrics = await this.getPerformanceMetrics();\n \n if (!systemMetrics && !perfMetrics) {\n return 'error';\n }\n \n // Check memory usage\n if (systemMetrics && systemMetrics.memoryUsagePercent > 90) {\n return 'error';\n }\n \n if (systemMetrics && systemMetrics.memoryUsagePercent > 75) {\n return 'warning';\n }\n \n // Check CPU load\n if (systemMetrics && systemMetrics.cpuLoad > 0.8) {\n return 'warning';\n }\n \n // Check task failure rate\n if (perfMetrics && perfMetrics.totalTasks > 0) {\n const failureRate = perfMetrics.failedTasks / perfMetrics.totalTasks;\n if (failureRate > 0.5) {\n return 'error';\n }\n if (failureRate > 0.2) {\n return 'warning';\n }\n }\n \n return 'healthy';\n } catch (error) {\n return 'error';\n }\n }\n\n async getSessionFiles() {\n try {\n const files = await fs.readdir(path.join(this.sessionsDir, 'pair'));\n return files.filter(f => f.endsWith('.json')).sort();\n } catch (error) {\n return [];\n }\n }\n\n async getMCPServerStatus() {\n try {\n // Check if MCP server process is running (including flow-nexus and other MCP variants)\n const { stdout } = await execAsync('ps aux | grep -E \"mcp\" | grep -v grep | wc -l');\n const processCount = parseInt(stdout.trim(), 10);\n \n // Check for orchestrator running\n const { stdout: orchestratorOut } = await execAsync('ps aux | grep -E \"claude-flow start\" | grep -v grep | wc -l');\n const orchestratorRunning = parseInt(orchestratorOut.trim(), 10) > 0;\n \n // Determine status\n const isRunning = processCount > 0;\n \n // Try to get port from process (default is 3000)\n let port = 3000;\n try {\n const { stdout: portOut } = await execAsync('lsof -i :3000 2>/dev/null | grep LISTEN | wc -l');\n if (parseInt(portOut.trim(), 10) === 0) {\n // If port 3000 not listening, check other common ports\n port = null;\n }\n } catch {\n // lsof might not be available or port not in use\n }\n \n return {\n running: isRunning,\n processCount,\n orchestratorRunning,\n port,\n connections: processCount > 0 ? Math.max(1, processCount - 1) : 0 // Estimate connections\n };\n } catch (error) {\n // Fallback if commands fail\n return {\n running: false,\n processCount: 0,\n orchestratorRunning: false,\n port: null,\n connections: 0\n };\n }\n }\n}\n\nexport { MetricsReader };"],"names":["promises","fs","path","exec","promisify","execAsync","MetricsReader","metricsDir","sessionsDir","getSystemMetrics","filePath","join","content","readFile","metrics","JSON","parse","length","error","getTaskQueue","queueFile","getTaskMetrics","getPerformanceMetrics","getActiveAgents","agents","agentsDir","agentFiles","readdir","file","endsWith","agent","push","sessionFiles","getSessionFiles","sessionData","Array","isArray","getSessionStatus","mostRecentFile","getRecentTasks","limit","taskMetrics","sort","a","b","timestamp","slice","map","task","id","type","status","success","startTime","duration","endTime","getOverallHealth","systemMetrics","perfMetrics","memoryUsagePercent","cpuLoad","totalTasks","failureRate","failedTasks","files","filter","f","getMCPServerStatus","stdout","processCount","parseInt","trim","orchestratorOut","orchestratorRunning","isRunning","port","portOut","running","connections","Math","max"],"mappings":"AAAA,SAASA,YAAYC,EAAE,QAAQ,KAAK;AACpC,OAAOC,UAAU,OAAO;AACxB,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AAEjC,MAAMC,YAAYD,UAAUD;AAE5B,IAAA,AAAMG,gBAAN,MAAMA;IACJ,aAAc;QACZ,IAAI,CAACC,UAAU,GAAG;QAClB,IAAI,CAACC,WAAW,GAAG;IACrB;IAEA,MAAMC,mBAAmB;QACvB,IAAI;YACF,MAAMC,WAAWR,KAAKS,IAAI,CAAC,IAAI,CAACJ,UAAU,EAAE;YAC5C,MAAMK,UAAU,MAAMX,GAAGY,QAAQ,CAACH,UAAU;YAC5C,MAAMI,UAAUC,KAAKC,KAAK,CAACJ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