claude-flow 2.7.17 → 2.7.19

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/bin/sh
2
2
  # Claude-Flow Smart Dispatcher - Detects and uses the best available runtime
3
3
 
4
- VERSION="2.7.17"
4
+ VERSION="2.7.19"
5
5
 
6
6
  # Determine the correct path based on how the script is invoked
7
7
  if [ -L "$0" ]; then
@@ -1,123 +1,265 @@
1
- import { Command } from 'commander';
2
- import chalk from 'chalk';
3
- import inquirer from 'inquirer';
4
- import { ProviderManager } from '../../execution/provider-manager.js';
5
- export function createConfigCommand() {
6
- const config = new Command('config').description('Manage provider configuration');
7
- config.command('set-provider').description('Set default provider').argument('<provider>', 'Provider name (anthropic, openrouter, onnx, gemini)').option('-m, --model <model>', 'Default model for provider').action(async (provider, options)=>{
8
- try {
9
- const manager = new ProviderManager();
10
- await manager.setDefaultProvider(provider);
11
- if (options.model) {
12
- await manager.configureProvider(provider, {
13
- model: options.model,
14
- enabled: true
15
- });
16
- }
17
- console.log(chalk.green(`✓ Default provider set to: ${provider}`));
18
- if (options.model) {
19
- console.log(chalk.green(`✓ Default model set to: ${options.model}`));
1
+ import { printSuccess, printError, printWarning, readJsonFile, writeJsonFile, fileExists } from '../utils.js';
2
+ export async function configCommand(subArgs, flags) {
3
+ const configCmd = subArgs[0];
4
+ switch(configCmd){
5
+ case 'init':
6
+ await initConfig(subArgs, flags);
7
+ break;
8
+ case 'show':
9
+ await showConfig(subArgs, flags);
10
+ break;
11
+ case 'get':
12
+ await getConfigValue(subArgs, flags);
13
+ break;
14
+ case 'set':
15
+ await setConfigValue(subArgs, flags);
16
+ break;
17
+ case 'validate':
18
+ await validateConfig(subArgs, flags);
19
+ break;
20
+ case 'reset':
21
+ await resetConfig(subArgs, flags);
22
+ break;
23
+ default:
24
+ showConfigHelp();
25
+ }
26
+ }
27
+ async function initConfig(subArgs, flags) {
28
+ const force = subArgs.includes('--force') || subArgs.includes('-f');
29
+ const configFile = 'claude-flow.config.json';
30
+ try {
31
+ const exists = await fileExists(configFile);
32
+ if (exists && !force) {
33
+ printWarning('Configuration file already exists');
34
+ console.log('Use --force to overwrite existing configuration');
35
+ return;
36
+ }
37
+ printSuccess('Initializing Claude-Flow configuration...');
38
+ const defaultConfig = {
39
+ version: '1.0.71',
40
+ terminal: {
41
+ poolSize: 10,
42
+ recycleAfter: 20,
43
+ healthCheckInterval: 30000,
44
+ type: 'auto'
45
+ },
46
+ orchestrator: {
47
+ maxConcurrentTasks: 10,
48
+ taskTimeout: 300000,
49
+ defaultPriority: 5
50
+ },
51
+ memory: {
52
+ backend: 'json',
53
+ path: './memory/claude-flow-data.json',
54
+ cacheSize: 1000,
55
+ indexing: true
56
+ },
57
+ agents: {
58
+ maxAgents: 20,
59
+ defaultCapabilities: [
60
+ 'research',
61
+ 'code',
62
+ 'terminal'
63
+ ],
64
+ resourceLimits: {
65
+ memory: '1GB',
66
+ cpu: '50%'
67
+ }
68
+ },
69
+ mcp: {
70
+ port: 3000,
71
+ host: 'localhost',
72
+ timeout: 30000
73
+ },
74
+ logging: {
75
+ level: 'info',
76
+ file: './claude-flow.log',
77
+ maxSize: '10MB',
78
+ maxFiles: 5
20
79
  }
21
- } catch (error) {
22
- console.error(chalk.red('✗ Error:'), error.message);
23
- process.exit(1);
80
+ };
81
+ await writeJsonFile(configFile, defaultConfig);
82
+ console.log(`✓ Created ${configFile}`);
83
+ console.log('✓ Default settings configured');
84
+ console.log('\nNext steps:');
85
+ console.log('1. Review settings: claude-flow config show');
86
+ console.log('2. Customize values: claude-flow config set <key> <value>');
87
+ console.log('3. Validate config: claude-flow config validate');
88
+ } catch (err) {
89
+ printError(`Failed to initialize configuration: ${err.message}`);
90
+ }
91
+ }
92
+ async function showConfig(subArgs, flags) {
93
+ const configFile = 'claude-flow.config.json';
94
+ const format = getFlag(subArgs, '--format') || 'pretty';
95
+ try {
96
+ const config = await readJsonFile(configFile);
97
+ printSuccess('Current configuration:');
98
+ if (format === 'json') {
99
+ console.log(JSON.stringify(config, null, 2));
100
+ } else {
101
+ console.log('\n📋 System Configuration:');
102
+ console.log(` Version: ${config.version || 'unknown'}`);
103
+ console.log('\n🖥️ Terminal Pool:');
104
+ console.log(` Pool Size: ${config.terminal?.poolSize || 10}`);
105
+ console.log(` Recycle After: ${config.terminal?.recycleAfter || 20} commands`);
106
+ console.log(` Health Check: ${config.terminal?.healthCheckInterval || 30000}ms`);
107
+ console.log('\n🎭 Orchestrator:');
108
+ console.log(` Max Concurrent Tasks: ${config.orchestrator?.maxConcurrentTasks || 10}`);
109
+ console.log(` Task Timeout: ${config.orchestrator?.taskTimeout || 300000}ms`);
110
+ console.log('\n💾 Memory:');
111
+ console.log(` Backend: ${config.memory?.backend || 'json'}`);
112
+ console.log(` Path: ${config.memory?.path || './memory/claude-flow-data.json'}`);
113
+ console.log('\n🤖 Agents:');
114
+ console.log(` Max Agents: ${config.agents?.maxAgents || 20}`);
115
+ console.log(` Resource Limits: ${JSON.stringify(config.agents?.resourceLimits || {})}`);
24
116
  }
25
- });
26
- config.command('list-providers').alias('list').description('List configured providers').option('-f, --format <format>', 'Output format (text, json)', 'text').action(async (options)=>{
27
- try {
28
- const manager = new ProviderManager();
29
- const providers = manager.listProviders();
30
- const defaultProvider = manager.getDefaultProvider();
31
- if (options.format === 'json') {
32
- console.log(JSON.stringify({
33
- defaultProvider,
34
- providers
35
- }, null, 2));
36
- } else {
37
- console.log(chalk.cyan('\n📋 Configured Providers:\n'));
38
- console.log(chalk.white(`Default: ${chalk.bold(defaultProvider)}\n`));
39
- providers.forEach((provider)=>{
40
- const isDefault = provider.name === defaultProvider;
41
- const prefix = isDefault ? chalk.green('●') : chalk.gray('○');
42
- const status = provider.enabled ? chalk.green('enabled') : chalk.gray('disabled');
43
- console.log(`${prefix} ${chalk.bold(provider.name)}`);
44
- console.log(` Model: ${provider.model || 'default'}`);
45
- console.log(` Priority: ${provider.priority || 'balanced'}`);
46
- console.log(` Status: ${status}`);
47
- console.log('');
48
- });
117
+ } catch (err) {
118
+ printError('Configuration file not found');
119
+ console.log('Run "claude-flow config init" to create default configuration');
120
+ }
121
+ }
122
+ async function getConfigValue(subArgs, flags) {
123
+ const key = subArgs[1];
124
+ const configFile = 'claude-flow.config.json';
125
+ if (!key) {
126
+ printError('Usage: config get <key>');
127
+ console.log('Examples:');
128
+ console.log(' claude-flow config get terminal.poolSize');
129
+ console.log(' claude-flow config get orchestrator.maxConcurrentTasks');
130
+ return;
131
+ }
132
+ try {
133
+ const config = await readJsonFile(configFile);
134
+ const value = getNestedValue(config, key);
135
+ if (value !== undefined) {
136
+ console.log(`${key}: ${JSON.stringify(value)}`);
137
+ } else {
138
+ printWarning(`Configuration key '${key}' not found`);
139
+ }
140
+ } catch (err) {
141
+ printError('Configuration file not found');
142
+ console.log('Run "claude-flow config init" to create configuration');
143
+ }
144
+ }
145
+ async function setConfigValue(subArgs, flags) {
146
+ const key = subArgs[1];
147
+ const value = subArgs[2];
148
+ const configFile = 'claude-flow.config.json';
149
+ if (!key || value === undefined) {
150
+ printError('Usage: config set <key> <value>');
151
+ console.log('Examples:');
152
+ console.log(' claude-flow config set terminal.poolSize 15');
153
+ console.log(' claude-flow config set orchestrator.taskTimeout 600000');
154
+ return;
155
+ }
156
+ try {
157
+ let config = await readJsonFile(configFile, {});
158
+ let parsedValue = value;
159
+ if (value === 'true') parsedValue = true;
160
+ else if (value === 'false') parsedValue = false;
161
+ else if (!isNaN(value) && value.trim() !== '') parsedValue = Number(value);
162
+ setNestedValue(config, key, parsedValue);
163
+ await writeJsonFile(configFile, config);
164
+ printSuccess(`Set ${key} = ${JSON.stringify(parsedValue)}`);
165
+ } catch (err) {
166
+ printError(`Failed to set configuration: ${err.message}`);
167
+ }
168
+ }
169
+ async function validateConfig(subArgs, flags) {
170
+ const configFile = 'claude-flow.config.json';
171
+ try {
172
+ const config = await readJsonFile(configFile);
173
+ printSuccess('Validating configuration...');
174
+ const errors = [];
175
+ const warnings = [];
176
+ const requiredSections = [
177
+ 'terminal',
178
+ 'orchestrator',
179
+ 'memory'
180
+ ];
181
+ for (const section of requiredSections){
182
+ if (!config[section]) {
183
+ errors.push(`Missing required section: ${section}`);
49
184
  }
50
- } catch (error) {
51
- console.error(chalk.red('✗ Error:'), error.message);
52
- process.exit(1);
53
185
  }
54
- });
55
- config.command('wizard').description('Interactive provider configuration wizard').action(async ()=>{
56
- try {
57
- const manager = new ProviderManager();
58
- console.log(chalk.cyan('\n🧙 Provider Configuration Wizard\n'));
59
- const answers = await inquirer.prompt([
60
- {
61
- type: 'list',
62
- name: 'defaultProvider',
63
- message: 'Select default provider:',
64
- choices: [
65
- {
66
- name: 'Anthropic (Highest quality)',
67
- value: 'anthropic'
68
- },
69
- {
70
- name: 'OpenRouter (99% cost savings)',
71
- value: 'openrouter'
72
- },
73
- {
74
- name: 'ONNX (Free local inference)',
75
- value: 'onnx'
76
- },
77
- {
78
- name: 'Gemini (Free tier)',
79
- value: 'gemini'
80
- }
81
- ]
82
- },
83
- {
84
- type: 'list',
85
- name: 'optimization',
86
- message: 'Optimization priority:',
87
- choices: [
88
- {
89
- name: 'Balanced (recommended)',
90
- value: 'balanced'
91
- },
92
- {
93
- name: 'Cost (cheapest)',
94
- value: 'cost'
95
- },
96
- {
97
- name: 'Quality (best results)',
98
- value: 'quality'
99
- },
100
- {
101
- name: 'Speed (fastest)',
102
- value: 'speed'
103
- },
104
- {
105
- name: 'Privacy (local only)',
106
- value: 'privacy'
107
- }
108
- ]
109
- }
110
- ]);
111
- await manager.setDefaultProvider(answers.defaultProvider);
112
- console.log(chalk.green('\n✓ Configuration saved successfully!'));
113
- console.log(chalk.gray(`\nDefault provider: ${answers.defaultProvider}`));
114
- console.log(chalk.gray(`Optimization: ${answers.optimization}`));
115
- } catch (error) {
116
- console.error(chalk.red('\n✗ Error:'), error.message);
117
- process.exit(1);
186
+ if (config.terminal?.poolSize && (config.terminal.poolSize < 1 || config.terminal.poolSize > 100)) {
187
+ warnings.push('Terminal pool size should be between 1 and 100');
118
188
  }
119
- });
120
- return config;
189
+ if (config.orchestrator?.maxConcurrentTasks && config.orchestrator.maxConcurrentTasks < 1) {
190
+ errors.push('Max concurrent tasks must be at least 1');
191
+ }
192
+ if (config.agents?.maxAgents && config.agents.maxAgents < 1) {
193
+ errors.push('Max agents must be at least 1');
194
+ }
195
+ if (errors.length === 0 && warnings.length === 0) {
196
+ printSuccess('✅ Configuration is valid');
197
+ } else {
198
+ if (errors.length > 0) {
199
+ printError(`Found ${errors.length} error(s):`);
200
+ errors.forEach((error)=>console.log(` ❌ ${error}`));
201
+ }
202
+ if (warnings.length > 0) {
203
+ printWarning(`Found ${warnings.length} warning(s):`);
204
+ warnings.forEach((warning)=>console.log(` ⚠️ ${warning}`));
205
+ }
206
+ }
207
+ } catch (err) {
208
+ printError('Configuration file not found or invalid');
209
+ console.log('Run "claude-flow config init" to create valid configuration');
210
+ }
211
+ }
212
+ async function resetConfig(subArgs, flags) {
213
+ const force = subArgs.includes('--force') || subArgs.includes('-f');
214
+ if (!force) {
215
+ printWarning('This will reset configuration to defaults');
216
+ console.log('Use --force to confirm reset');
217
+ return;
218
+ }
219
+ await initConfig([
220
+ '--force'
221
+ ], flags);
222
+ printSuccess('Configuration reset to defaults');
223
+ }
224
+ function getNestedValue(obj, path) {
225
+ return path.split('.').reduce((current, key)=>current?.[key], obj);
226
+ }
227
+ function setNestedValue(obj, path, value) {
228
+ const keys = path.split('.');
229
+ const last = keys.pop();
230
+ const target = keys.reduce((current, key)=>{
231
+ if (!current[key]) current[key] = {};
232
+ return current[key];
233
+ }, obj);
234
+ target[last] = value;
235
+ }
236
+ function getFlag(args, flagName) {
237
+ const index = args.indexOf(flagName);
238
+ return index !== -1 && index + 1 < args.length ? args[index + 1] : null;
239
+ }
240
+ function showConfigHelp() {
241
+ console.log('Configuration commands:');
242
+ console.log(' init [--force] Create default configuration');
243
+ console.log(' show [--format json] Display current configuration');
244
+ console.log(' get <key> Get configuration value');
245
+ console.log(' set <key> <value> Set configuration value');
246
+ console.log(' validate Validate configuration');
247
+ console.log(' reset --force Reset to defaults');
248
+ console.log();
249
+ console.log('Configuration Keys:');
250
+ console.log(' terminal.poolSize Terminal pool size');
251
+ console.log(' terminal.recycleAfter Commands before recycle');
252
+ console.log(' orchestrator.maxConcurrentTasks Max parallel tasks');
253
+ console.log(' orchestrator.taskTimeout Task timeout in ms');
254
+ console.log(' memory.backend Memory storage backend');
255
+ console.log(' memory.path Memory database path');
256
+ console.log(' agents.maxAgents Maximum number of agents');
257
+ console.log();
258
+ console.log('Examples:');
259
+ console.log(' claude-flow config init');
260
+ console.log(' claude-flow config set terminal.poolSize 15');
261
+ console.log(' claude-flow config get orchestrator.maxConcurrentTasks');
262
+ console.log(' claude-flow config validate');
121
263
  }
122
264
 
123
265
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/cli/simple-commands/config.ts"],"sourcesContent":["/**\n * Config CLI Commands - Manage provider configuration\n */\n\nimport { Command } from 'commander';\nimport chalk from 'chalk';\nimport inquirer from 'inquirer';\nimport { ProviderManager } from '../../execution/provider-manager.js';\n\nexport function createConfigCommand(): Command {\n const config = new Command('config')\n .description('Manage provider configuration');\n\n // config set-provider command\n config\n .command('set-provider')\n .description('Set default provider')\n .argument('<provider>', 'Provider name (anthropic, openrouter, onnx, gemini)')\n .option('-m, --model <model>', 'Default model for provider')\n .action(async (provider, options) => {\n try {\n const manager = new ProviderManager();\n\n await manager.setDefaultProvider(provider);\n\n if (options.model) {\n await manager.configureProvider(provider, {\n model: options.model,\n enabled: true,\n } as any);\n }\n\n console.log(chalk.green(`✓ Default provider set to: ${provider}`));\n if (options.model) {\n console.log(chalk.green(`✓ Default model set to: ${options.model}`));\n }\n } catch (error: any) {\n console.error(chalk.red('✗ Error:'), error.message);\n process.exit(1);\n }\n });\n\n // config list-providers command\n config\n .command('list-providers')\n .alias('list')\n .description('List configured providers')\n .option('-f, --format <format>', 'Output format (text, json)', 'text')\n .action(async (options) => {\n try {\n const manager = new ProviderManager();\n const providers = manager.listProviders();\n const defaultProvider = manager.getDefaultProvider();\n\n if (options.format === 'json') {\n console.log(JSON.stringify({ defaultProvider, providers }, null, 2));\n } else {\n console.log(chalk.cyan('\\n📋 Configured Providers:\\n'));\n console.log(chalk.white(`Default: ${chalk.bold(defaultProvider)}\\n`));\n\n providers.forEach(provider => {\n const isDefault = provider.name === defaultProvider;\n const prefix = isDefault ? chalk.green('●') : chalk.gray('○');\n const status = provider.enabled ? chalk.green('enabled') : chalk.gray('disabled');\n\n console.log(`${prefix} ${chalk.bold(provider.name)}`);\n console.log(` Model: ${provider.model || 'default'}`);\n console.log(` Priority: ${provider.priority || 'balanced'}`);\n console.log(` Status: ${status}`);\n console.log('');\n });\n }\n } catch (error: any) {\n console.error(chalk.red('✗ Error:'), error.message);\n process.exit(1);\n }\n });\n\n // config wizard command\n config\n .command('wizard')\n .description('Interactive provider configuration wizard')\n .action(async () => {\n try {\n const manager = new ProviderManager();\n\n console.log(chalk.cyan('\\n🧙 Provider Configuration Wizard\\n'));\n\n const answers = await inquirer.prompt([\n {\n type: 'list',\n name: 'defaultProvider',\n message: 'Select default provider:',\n choices: [\n { name: 'Anthropic (Highest quality)', value: 'anthropic' },\n { name: 'OpenRouter (99% cost savings)', value: 'openrouter' },\n { name: 'ONNX (Free local inference)', value: 'onnx' },\n { name: 'Gemini (Free tier)', value: 'gemini' },\n ],\n },\n {\n type: 'list',\n name: 'optimization',\n message: 'Optimization priority:',\n choices: [\n { name: 'Balanced (recommended)', value: 'balanced' },\n { name: 'Cost (cheapest)', value: 'cost' },\n { name: 'Quality (best results)', value: 'quality' },\n { name: 'Speed (fastest)', value: 'speed' },\n { name: 'Privacy (local only)', value: 'privacy' },\n ],\n },\n ]);\n\n await manager.setDefaultProvider(answers.defaultProvider);\n\n console.log(chalk.green('\\n✓ Configuration saved successfully!'));\n console.log(chalk.gray(`\\nDefault provider: ${answers.defaultProvider}`));\n console.log(chalk.gray(`Optimization: ${answers.optimization}`));\n } catch (error: any) {\n console.error(chalk.red('\\n✗ Error:'), error.message);\n process.exit(1);\n }\n });\n\n return config;\n}\n"],"names":["Command","chalk","inquirer","ProviderManager","createConfigCommand","config","description","command","argument","option","action","provider","options","manager","setDefaultProvider","model","configureProvider","enabled","console","log","green","error","red","message","process","exit","alias","providers","listProviders","defaultProvider","getDefaultProvider","format","JSON","stringify","cyan","white","bold","forEach","isDefault","name","prefix","gray","status","priority","answers","prompt","type","choices","value","optimization"],"mappings":"AAIA,SAASA,OAAO,QAAQ,YAAY;AACpC,OAAOC,WAAW,QAAQ;AAC1B,OAAOC,cAAc,WAAW;AAChC,SAASC,eAAe,QAAQ,sCAAsC;AAEtE,OAAO,SAASC;IACd,MAAMC,SAAS,IAAIL,QAAQ,UACxBM,WAAW,CAAC;IAGfD,OACGE,OAAO,CAAC,gBACRD,WAAW,CAAC,wBACZE,QAAQ,CAAC,cAAc,uDACvBC,MAAM,CAAC,uBAAuB,8BAC9BC,MAAM,CAAC,OAAOC,UAAUC;QACvB,IAAI;YACF,MAAMC,UAAU,IAAIV;YAEpB,MAAMU,QAAQC,kBAAkB,CAACH;YAEjC,IAAIC,QAAQG,KAAK,EAAE;gBACjB,MAAMF,QAAQG,iBAAiB,CAACL,UAAU;oBACxCI,OAAOH,QAAQG,KAAK;oBACpBE,SAAS;gBACX;YACF;YAEAC,QAAQC,GAAG,CAAClB,MAAMmB,KAAK,CAAC,CAAC,2BAA2B,EAAET,UAAU;YAChE,IAAIC,QAAQG,KAAK,EAAE;gBACjBG,QAAQC,GAAG,CAAClB,MAAMmB,KAAK,CAAC,CAAC,wBAAwB,EAAER,QAAQG,KAAK,EAAE;YACpE;QACF,EAAE,OAAOM,OAAY;YACnBH,QAAQG,KAAK,CAACpB,MAAMqB,GAAG,CAAC,aAAaD,MAAME,OAAO;YAClDC,QAAQC,IAAI,CAAC;QACf;IACF;IAGFpB,OACGE,O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],"sourcesContent":["// config.js - Configuration management commands\nimport {\n printSuccess,\n printError,\n printWarning,\n readJsonFile,\n writeJsonFile,\n fileExists,\n} from '../utils.js';\n\nexport async function configCommand(subArgs, flags) {\n const configCmd = subArgs[0];\n\n switch (configCmd) {\n case 'init':\n await initConfig(subArgs, flags);\n break;\n\n case 'show':\n await showConfig(subArgs, flags);\n break;\n\n case 'get':\n await getConfigValue(subArgs, flags);\n break;\n\n case 'set':\n await setConfigValue(subArgs, flags);\n break;\n\n case 'validate':\n await validateConfig(subArgs, flags);\n break;\n\n case 'reset':\n await resetConfig(subArgs, flags);\n break;\n\n default:\n showConfigHelp();\n }\n}\n\nasync function initConfig(subArgs, flags) {\n const force = subArgs.includes('--force') || subArgs.includes('-f');\n const configFile = 'claude-flow.config.json';\n\n try {\n // Check if config already exists\n const exists = await fileExists(configFile);\n if (exists && !force) {\n printWarning('Configuration file already exists');\n console.log('Use --force to overwrite existing configuration');\n return;\n }\n\n printSuccess('Initializing Claude-Flow configuration...');\n\n // Create default configuration\n const defaultConfig = {\n version: '1.0.71',\n terminal: {\n poolSize: 10,\n recycleAfter: 20,\n healthCheckInterval: 30000,\n type: 'auto',\n },\n orchestrator: {\n maxConcurrentTasks: 10,\n taskTimeout: 300000,\n defaultPriority: 5,\n },\n memory: {\n backend: 'json',\n path: './memory/claude-flow-data.json',\n cacheSize: 1000,\n indexing: true,\n },\n agents: {\n maxAgents: 20,\n defaultCapabilities: ['research', 'code', 'terminal'],\n resourceLimits: {\n memory: '1GB',\n cpu: '50%',\n },\n },\n mcp: {\n port: 3000,\n host: 'localhost',\n timeout: 30000,\n },\n logging: {\n level: 'info',\n file: './claude-flow.log',\n maxSize: '10MB',\n maxFiles: 5,\n },\n };\n\n await writeJsonFile(configFile, defaultConfig);\n console.log(`✓ Created ${configFile}`);\n console.log('✓ Default settings configured');\n console.log('\\nNext steps:');\n console.log('1. Review settings: claude-flow config show');\n console.log('2. Customize values: claude-flow config set <key> <value>');\n console.log('3. Validate config: claude-flow config validate');\n } catch (err) {\n printError(`Failed to initialize configuration: ${err.message}`);\n }\n}\n\nasync function showConfig(subArgs, flags) {\n const configFile = 'claude-flow.config.json';\n const format = getFlag(subArgs, '--format') || 'pretty';\n\n try {\n const config = await readJsonFile(configFile);\n\n printSuccess('Current configuration:');\n\n if (format === 'json') {\n console.log(JSON.stringify(config, null, 2));\n } else {\n // Pretty format\n console.log('\\n📋 System Configuration:');\n console.log(` Version: ${config.version || 'unknown'}`);\n console.log('\\n🖥️ Terminal Pool:');\n console.log(` Pool Size: ${config.terminal?.poolSize || 10}`);\n console.log(` Recycle After: ${config.terminal?.recycleAfter || 20} commands`);\n console.log(` Health Check: ${config.terminal?.healthCheckInterval || 30000}ms`);\n console.log('\\n🎭 Orchestrator:');\n console.log(` Max Concurrent Tasks: ${config.orchestrator?.maxConcurrentTasks || 10}`);\n console.log(` Task Timeout: ${config.orchestrator?.taskTimeout || 300000}ms`);\n console.log('\\n💾 Memory:');\n console.log(` Backend: ${config.memory?.backend || 'json'}`);\n console.log(` Path: ${config.memory?.path || './memory/claude-flow-data.json'}`);\n console.log('\\n🤖 Agents:');\n console.log(` Max Agents: ${config.agents?.maxAgents || 20}`);\n console.log(` Resource Limits: ${JSON.stringify(config.agents?.resourceLimits || {})}`);\n }\n } catch (err) {\n printError('Configuration file not found');\n console.log('Run \"claude-flow config init\" to create default configuration');\n }\n}\n\nasync function getConfigValue(subArgs, flags) {\n const key = subArgs[1];\n const configFile = 'claude-flow.config.json';\n\n if (!key) {\n printError('Usage: config get <key>');\n console.log('Examples:');\n console.log(' claude-flow config get terminal.poolSize');\n console.log(' claude-flow config get orchestrator.maxConcurrentTasks');\n return;\n }\n\n try {\n const config = await readJsonFile(configFile);\n const value = getNestedValue(config, key);\n\n if (value !== undefined) {\n console.log(`${key}: ${JSON.stringify(value)}`);\n } else {\n printWarning(`Configuration key '${key}' not found`);\n }\n } catch (err) {\n printError('Configuration file not found');\n console.log('Run \"claude-flow config init\" to create configuration');\n }\n}\n\nasync function setConfigValue(subArgs, flags) {\n const key = subArgs[1];\n const value = subArgs[2];\n const configFile = 'claude-flow.config.json';\n\n if (!key || value === undefined) {\n printError('Usage: config set <key> <value>');\n console.log('Examples:');\n console.log(' claude-flow config set terminal.poolSize 15');\n console.log(' claude-flow config set orchestrator.taskTimeout 600000');\n return;\n }\n\n try {\n let config = await readJsonFile(configFile, {});\n\n // Parse value appropriately\n let parsedValue = value;\n if (value === 'true') parsedValue = true;\n else if (value === 'false') parsedValue = false;\n else if (!isNaN(value) && value.trim() !== '') parsedValue = Number(value);\n\n // Set nested value\n setNestedValue(config, key, parsedValue);\n\n await writeJsonFile(configFile, config);\n printSuccess(`Set ${key} = ${JSON.stringify(parsedValue)}`);\n } catch (err) {\n printError(`Failed to set configuration: ${err.message}`);\n }\n}\n\nasync function validateConfig(subArgs, flags) {\n const configFile = 'claude-flow.config.json';\n\n try {\n const config = await readJsonFile(configFile);\n\n printSuccess('Validating configuration...');\n\n const errors = [];\n const warnings = [];\n\n // Validate required sections\n const requiredSections = ['terminal', 'orchestrator', 'memory'];\n for (const section of requiredSections) {\n if (!config[section]) {\n errors.push(`Missing required section: ${section}`);\n }\n }\n\n // Validate specific values\n if (\n config.terminal?.poolSize &&\n (config.terminal.poolSize < 1 || config.terminal.poolSize > 100)\n ) {\n warnings.push('Terminal pool size should be between 1 and 100');\n }\n\n if (config.orchestrator?.maxConcurrentTasks && config.orchestrator.maxConcurrentTasks < 1) {\n errors.push('Max concurrent tasks must be at least 1');\n }\n\n if (config.agents?.maxAgents && config.agents.maxAgents < 1) {\n errors.push('Max agents must be at least 1');\n }\n\n // Report results\n if (errors.length === 0 && warnings.length === 0) {\n printSuccess('✅ Configuration is valid');\n } else {\n if (errors.length > 0) {\n printError(`Found ${errors.length} error(s):`);\n errors.forEach((error) => console.log(` ❌ ${error}`));\n }\n\n if (warnings.length > 0) {\n printWarning(`Found ${warnings.length} warning(s):`);\n warnings.forEach((warning) => console.log(` ⚠️ ${warning}`));\n }\n }\n } catch (err) {\n printError('Configuration file not found or invalid');\n console.log('Run \"claude-flow config init\" to create valid configuration');\n }\n}\n\nasync function resetConfig(subArgs, flags) {\n const force = subArgs.includes('--force') || subArgs.includes('-f');\n\n if (!force) {\n printWarning('This will reset configuration to defaults');\n console.log('Use --force to confirm reset');\n return;\n }\n\n await initConfig(['--force'], flags);\n printSuccess('Configuration reset to defaults');\n}\n\n// Helper functions\nfunction getNestedValue(obj, path) {\n return path.split('.').reduce((current, key) => current?.[key], obj);\n}\n\nfunction setNestedValue(obj, path, value) {\n const keys = path.split('.');\n const last = keys.pop();\n const target = keys.reduce((current, key) => {\n if (!current[key]) current[key] = {};\n return current[key];\n }, obj);\n target[last] = value;\n}\n\nfunction getFlag(args, flagName) {\n const index = args.indexOf(flagName);\n return index !== -1 && index + 1 < args.length ? args[index + 1] : null;\n}\n\n// fileExists is now imported from utils.js\n\nfunction showConfigHelp() {\n console.log('Configuration commands:');\n console.log(' init [--force] Create default configuration');\n console.log(' show [--format json] Display current configuration');\n console.log(' get <key> Get configuration value');\n console.log(' set <key> <value> Set configuration value');\n console.log(' validate Validate configuration');\n console.log(' reset --force Reset to defaults');\n console.log();\n console.log('Configuration Keys:');\n console.log(' terminal.poolSize Terminal pool size');\n console.log(' terminal.recycleAfter Commands before recycle');\n console.log(' orchestrator.maxConcurrentTasks Max parallel tasks');\n console.log(' orchestrator.taskTimeout Task timeout in ms');\n console.log(' memory.backend Memory storage backend');\n console.log(' memory.path Memory database path');\n console.log(' agents.maxAgents Maximum number of agents');\n console.log();\n console.log('Examples:');\n console.log(' claude-flow config init');\n console.log(' claude-flow config set terminal.poolSize 15');\n console.log(' claude-flow config get orchestrator.maxConcurrentTasks');\n console.log(' claude-flow config validate');\n}\n"],"names":["printSuccess","printError","printWarning","readJsonFile","writeJsonFile","fileExists","configCommand","subArgs","flags","configCmd","initConfig","showConfig","getConfigValue","setConfigValue","validateConfig","resetConfig","showConfigHelp","force","includes","configFile","exists","console","log","defaultConfig","version","terminal","poolSize","recycleAfter","healthCheckInterval","type","orchestrator","maxConcurrentTasks","taskTimeout","defaultPriority","memory","backend","path","cacheSize","indexing","agents","maxAgents","defaultCapabilities","resourceLimits","cpu","mcp","port","host","timeout","logging","level","file","maxSize","maxFiles","err","message","format","getFlag","config","JSON","stringify","key","value","getNestedValue","undefined","parsedValue","isNaN","trim","Number","setNestedValue","errors","warnings","requiredSections","section","push","length","forEach","error","warning","obj","split","reduce","current","keys","last","pop","target","args","flagName","index","indexOf"],"mappings":"AACA,SACEA,YAAY,EACZC,UAAU,EACVC,YAAY,EACZC,YAAY,EACZC,aAAa,EACbC,UAAU,QACL,cAAc;AAErB,OAAO,eAAeC,cAAcC,OAAO,EAAEC,KAAK;IAChD,MAAMC,YAAYF,OAAO,CAAC,EAAE;IAE5B,OAAQE;QACN,KAAK;YACH,MAAMC,WAAWH,SAASC;YAC1B;QAEF,KAAK;YACH,MAAMG,WAAWJ,SAASC;YAC1B;QAEF,KAAK;YACH,MAAMI,eAAeL,SAASC;YAC9B;QAEF,KAAK;YACH,MAAMK,eAAeN,SAASC;YAC9B;QAEF,KAAK;YACH,MAAMM,eAAeP,SAASC;YAC9B;QAEF,KAAK;YACH,MAAMO,YAAYR,SAASC;YAC3B;QAEF;YACEQ;IACJ;AACF;AAEA,eAAeN,WAAWH,OAAO,EAAEC,KAAK;IACtC,MAAMS,QAAQV,QAAQW,QAAQ,CAAC,cAAcX,QAAQW,QAAQ,CAAC;IAC9D,MAAMC,aAAa;IAEnB,IAAI;QAEF,MAAMC,SAAS,MAAMf,WAAWc;QAChC,IAAIC,UAAU,CAACH,OAAO;YACpBf,aAAa;YACbmB,QAAQC,GAAG,CAAC;YACZ;QACF;QAEAtB,aAAa;QAGb,MAAMuB,gBAAgB;YACpBC,SAAS;YACTC,UAAU;gBACRC,UAAU;gBACVC,cAAc;gBACdC,qBAAqB;gBACrBC,MAAM;YACR;YACAC,cAAc;gBACZC,oBAAoB;gBACpBC,aAAa;gBACbC,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d"}
@@ -324,7 +324,16 @@ async function detectMemoryMode(flags, subArgs) {
324
324
  }
325
325
  try {
326
326
  const { initializeReasoningBank } = await import('../../reasoningbank/reasoningbank-adapter.js');
327
- await initializeReasoningBank();
327
+ const initialized = await initializeReasoningBank();
328
+ if (!initialized) {
329
+ const isNpx = process.env.npm_config_user_agent?.includes('npx') || process.cwd().includes('_npx');
330
+ if (isNpx) {
331
+ console.log('\n✅ Automatically using JSON fallback for this command\n');
332
+ } else {
333
+ printWarning(`⚠️ SQLite unavailable, using JSON fallback`);
334
+ }
335
+ return 'basic';
336
+ }
328
337
  printInfo('🗄️ Initialized SQLite backend (.swarm/memory.db)');
329
338
  return 'reasoningbank';
330
339
  } catch (error) {
@@ -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 // Explicit basic mode flag\n if (flags?.basic || subArgs.includes('--basic')) {\n return 'basic';\n }\n\n // Default: AUTO MODE with SQLite preference\n // Try to use ReasoningBank (SQLite) by default, initialize if needed\n const initialized = await isReasoningBankInitialized();\n\n if (initialized) {\n return 'reasoningbank';\n }\n\n // Not initialized yet - try to auto-initialize on first use\n try {\n const { initializeReasoningBank } = await import('../../reasoningbank/reasoningbank-adapter.js');\n await initializeReasoningBank();\n printInfo('🗄️ Initialized SQLite backend (.swarm/memory.db)');\n return 'reasoningbank';\n } catch (error) {\n // SQLite initialization failed - fall back to JSON\n const isSqliteError = error.message?.includes('BetterSqlite3') ||\n error.message?.includes('better-sqlite3') ||\n error.message?.includes('could not run migrations') ||\n error.message?.includes('ReasoningBank initialization failed');\n const isNpx = process.env.npm_config_user_agent?.includes('npx') ||\n process.cwd().includes('_npx');\n\n if (isSqliteError && isNpx) {\n // Silent fallback for npx - error already shown by adapter\n console.log('\\n✅ Automatically using JSON fallback for this command\\n');\n return 'basic';\n } else {\n printWarning(`⚠️ SQLite unavailable, using JSON fallback`);\n printWarning(` Reason: ${error.message}`);\n return 'basic';\n }\n }\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, cleanup } = 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 } finally {\n // Cleanup after migration check\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\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 } finally {\n // Cleanup after init\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\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 } finally {\n // Always cleanup database connection\n cleanup();\n\n // Force process exit after cleanup (embedding cache timers prevent natural exit)\n // This is necessary because agentic-flow's embedding cache uses setTimeout\n // which keeps the event loop alive\n setTimeout(() => {\n process.exit(0);\n }, 100);\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","initializeReasoningBank","error","isSqliteError","isNpx","process","env","npm_config_user_agent","cwd","dbPath","access","command","queryMemories","listMemories","getStatus","checkReasoningBankTables","migrateReasoningBank","cleanup","CLAUDE_FLOW_DB_PATH","tableCheck","exists","missingTables","migrationResult","success","addedTables","setTimeout","exit","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,cA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AC;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,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"}
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 with SQLite preference\n // Try to use ReasoningBank (SQLite) by default, initialize if needed\n const initialized = await isReasoningBankInitialized();\n\n if (initialized) {\n return 'reasoningbank';\n }\n\n // Not initialized yet - try to auto-initialize on first use\n try {\n const { initializeReasoningBank } = await import('../../reasoningbank/reasoningbank-adapter.js');\n const initialized = await initializeReasoningBank();\n\n // Check if initialization succeeded (returns true) or failed (returns false)\n if (!initialized) {\n // Initialization failed but didn't throw - fall back to JSON\n const isNpx = process.env.npm_config_user_agent?.includes('npx') ||\n process.cwd().includes('_npx');\n if (isNpx) {\n console.log('\\n✅ Automatically using JSON fallback for this command\\n');\n } else {\n printWarning(`⚠️ SQLite unavailable, using JSON fallback`);\n }\n return 'basic';\n }\n\n printInfo('🗄️ Initialized SQLite backend (.swarm/memory.db)');\n return 'reasoningbank';\n } catch (error) {\n // SQLite initialization failed - fall back to JSON\n const isSqliteError = error.message?.includes('BetterSqlite3') ||\n error.message?.includes('better-sqlite3') ||\n error.message?.includes('could not run migrations') ||\n error.message?.includes('ReasoningBank initialization failed');\n const isNpx = process.env.npm_config_user_agent?.includes('npx') ||\n process.cwd().includes('_npx');\n\n if (isSqliteError && isNpx) {\n // Silent fallback for npx - error already shown by adapter\n console.log('\\n✅ Automatically using JSON fallback for this command\\n');\n return 'basic';\n } else {\n printWarning(`⚠️ SQLite unavailable, using JSON fallback`);\n printWarning(` Reason: ${error.message}`);\n return 'basic';\n }\n }\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, cleanup } = 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 } finally {\n // Cleanup after migration check\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\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 } finally {\n // Cleanup after init\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\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 } finally {\n // Always cleanup database connection\n cleanup();\n\n // Force process exit after cleanup (embedding cache timers prevent natural exit)\n // This is necessary because agentic-flow's embedding cache uses setTimeout\n // which keeps the event loop alive\n setTimeout(() => {\n process.exit(0);\n }, 100);\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","initializeReasoningBank","isNpx","process","env","npm_config_user_agent","cwd","error","isSqliteError","dbPath","access","command","queryMemories","listMemories","getStatus","checkReasoningBankTables","migrateReasoningBank","cleanup","CLAUDE_FLOW_DB_PATH","tableCheck","exists","missingTables","migrationResult","success","addedTables","setTimeout","exit","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,UA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;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,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"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/cli/validation-helper.js"],"sourcesContent":["/**\n * CLI Parameter Validation Helper\n * Provides standardized error messages for invalid parameters\n */\n\nimport { HelpFormatter } from './help-formatter.js';\n\nexport class ValidationHelper {\n /**\n * Validate enum parameter\n */\n static validateEnum(value, paramName, validOptions, commandPath) {\n if (!validOptions.includes(value)) {\n console.error(\n HelpFormatter.formatValidationError(value, paramName, validOptions, commandPath),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate numeric parameter\n */\n static validateNumber(value, paramName, min, max, commandPath) {\n const num = parseInt(value, 10);\n\n if (isNaN(num)) {\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid number for ${paramName}.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (min !== undefined && num < min) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at least ${min}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (max !== undefined && num > max) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at most ${max}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n return num;\n }\n\n /**\n * Validate required parameter\n */\n static validateRequired(value, paramName, commandPath) {\n if (!value || (typeof value === 'string' && value.trim() === '')) {\n console.error(\n HelpFormatter.formatError(\n `Missing required parameter: ${paramName}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate file path exists\n */\n static async validateFilePath(path, paramName, commandPath) {\n try {\n const fs = await import('fs/promises');\n await fs.access(path);\n } catch (error) {\n console.error(\n HelpFormatter.formatError(\n `File not found for ${paramName}: ${path}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate boolean flag\n */\n static validateBoolean(value, paramName, commandPath) {\n const lowerValue = value.toLowerCase();\n if (lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes') {\n return true;\n }\n if (lowerValue === 'false' || lowerValue === '0' || lowerValue === 'no') {\n return false;\n }\n\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid boolean for ${paramName}. Use: true, false, yes, no, 1, or 0.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n}\n"],"names":["HelpFormatter","ValidationHelper","validateEnum","value","paramName","validOptions","commandPath","includes","console","error","formatValidationError","process","exit","validateNumber","min","max","num","parseInt","isNaN","formatError","undefined","validateRequired","trim","validateFilePath","path","fs","access","validateBoolean","lowerValue","toLowerCase"],"mappings":"AAKA,SAASA,aAAa,QAAQ,sBAAsB;AAEpD,OAAO,MAAMC;IAIX,OAAOC,aAAaC,KAAK,EAAEC,SAAS,EAAEC,YAAY,EAAEC,WAAW,EAAE;QAC/D,IAAI,CAACD,aAAaE,QAAQ,CAACJ,QAAQ;YACjCK,QAAQC,KAAK,CACXT,cAAcU,qBAAqB,CAACP,OAAOC,WAAWC,cAAcC;YAEtEK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOC,eAAeV,KAAK,EAAEC,SAAS,EAAEU,GAAG,EAAEC,GAAG,EAAET,WAAW,EAAE;QAC7D,MAAMU,MAAMC,SAASd,OAAO;QAE5B,IAAIe,MAAMF,MAAM;YACdR,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,4BAA4B,EAAEC,UAAU,CAAC,CAAC,EACpDE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIE,QAAQM,aAAaJ,MAAMF,KAAK;YAClCN,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,kBAAkB,EAAEU,IAAI,OAAO,EAAEE,KAAK,EACnDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIG,QAAQK,aAAaJ,MAAMD,KAAK;YAClCP,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,iBAAiB,EAAEW,IAAI,OAAO,EAAEC,KAAK,EAClDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,OAAOI;IACT;IAKA,OAAOK,iBAAiBlB,KAAK,EAAEC,SAAS,EAAEE,WAAW,EAAE;QACrD,IAAI,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,"sources":["../../../src/cli/validation-helper.ts"],"sourcesContent":["/**\n * CLI Parameter Validation Helper\n * Provides standardized error messages for invalid parameters\n */\n\nimport { HelpFormatter } from './help-formatter.js';\n\nexport class ValidationHelper {\n /**\n * Validate enum parameter\n */\n static validateEnum(\n value: string,\n paramName: string,\n validOptions: string[],\n commandPath: string,\n ): void {\n if (!validOptions.includes(value)) {\n console.error(\n HelpFormatter.formatValidationError(value, paramName, validOptions, commandPath),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate numeric parameter\n */\n static validateNumber(\n value: string,\n paramName: string,\n min?: number,\n max?: number,\n commandPath?: string,\n ): number {\n const num = parseInt(value, 10);\n\n if (isNaN(num)) {\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid number for ${paramName}.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (min !== undefined && num < min) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at least ${min}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (max !== undefined && num > max) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at most ${max}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n return num;\n }\n\n /**\n * Validate required parameter\n */\n static validateRequired(value: any, paramName: string, commandPath?: string): void {\n if (!value || (typeof value === 'string' && value.trim() === '')) {\n console.error(\n HelpFormatter.formatError(\n `Missing required parameter: ${paramName}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate file path exists\n */\n static async validateFilePath(\n path: string,\n paramName: string,\n commandPath?: string,\n ): Promise<void> {\n try {\n const fs = await import('fs/promises');\n await fs.access(path);\n } catch (error) {\n console.error(\n HelpFormatter.formatError(\n `File not found for ${paramName}: ${path}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate boolean flag\n */\n static validateBoolean(value: string, paramName: string, commandPath?: string): boolean {\n const lowerValue = value.toLowerCase();\n if (lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes') {\n return true;\n }\n if (lowerValue === 'false' || lowerValue === '0' || lowerValue === 'no') {\n return false;\n }\n\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid boolean for ${paramName}. Use: true, false, yes, no, 1, or 0.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n}\n"],"names":["HelpFormatter","ValidationHelper","validateEnum","value","paramName","validOptions","commandPath","includes","console","error","formatValidationError","process","exit","validateNumber","min","max","num","parseInt","isNaN","formatError","undefined","validateRequired","trim","validateFilePath","path","fs","access","validateBoolean","lowerValue","toLowerCase"],"mappings":"AAKA,SAASA,aAAa,QAAQ,sBAAsB;AAEpD,OAAO,MAAMC;IAIX,OAAOC,aACLC,KAAa,EACbC,SAAiB,EACjBC,YAAsB,EACtBC,WAAmB,EACb;QACN,IAAI,CAACD,aAAaE,QAAQ,CAACJ,QAAQ;YACjCK,QAAQC,KAAK,CACXT,cAAcU,qBAAqB,CAACP,OAAOC,WAAWC,cAAcC;YAEtEK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOC,eACLV,KAAa,EACbC,SAAiB,EACjBU,GAAY,EACZC,GAAY,EACZT,WAAoB,EACZ;QACR,MAAMU,MAAMC,SAASd,OAAO;QAE5B,IAAIe,MAAMF,MAAM;YACdR,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,4BAA4B,EAAEC,UAAU,CAAC,CAAC,EACpDE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIE,QAAQM,aAAaJ,MAAMF,KAAK;YAClCN,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,kBAAkB,EAAEU,IAAI,OAAO,EAAEE,KAAK,EACnDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIG,QAAQK,aAAaJ,MAAMD,KAAK;YAClCP,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,iBAAiB,EAAEW,IAAI,OAAO,EAAEC,KAAK,EAClDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,OAAOI;IACT;IAKA,OAAOK,iBAAiBlB,KAAU,EAAEC,SAAiB,EAAEE,WAAoB,EAAQ;QACjF,IAAI,CAACH,SAAU,OAAOA,UAAU,YAAYA,MAAMmB,IAAI,OAAO,IAAK;YAChEd,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,4BAA4B,EAAEf,WAAW,EAC1CE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,aAAaW,iBACXC,IAAY,EACZpB,SAAiB,EACjBE,WAAoB,EACL;QACf,IAAI;YACF,MAAMmB,KAAK,MAAM,MAAM,CAAC;YACxB,MAAMA,GAAGC,MAAM,CAACF;QAClB,EAAE,OAAOf,OAAO;YACdD,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,mBAAmB,EAAEf,UAAU,EAAE,EAAEoB,MAAM,EAC1ClB,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOe,gBAAgBxB,KAAa,EAAEC,SAAiB,EAAEE,WAAoB,EAAW;QACtF,MAAMsB,aAAazB,MAAM0B,WAAW;QACpC,IAAID,eAAe,UAAUA,eAAe,OAAOA,eAAe,OAAO;YACvE,OAAO;QACT;QACA,IAAIA,eAAe,WAAWA,eAAe,OAAOA,eAAe,MAAM;YACvE,OAAO;QACT;QAEApB,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,6BAA6B,EAAEC,UAAU,qCAAqC,CAAC,EACzFE,eAAe;QAGnBK,QAAQC,IAAI,CAAC;IACf;AACF"}
@@ -19,31 +19,30 @@ async function ensureInitialized() {
19
19
  console.log('[ReasoningBank] Node.js backend initialized successfully');
20
20
  return true;
21
21
  } catch (error) {
22
- console.error('[ReasoningBank] Backend initialization failed:', error);
23
22
  const isSqliteError = error.message?.includes('BetterSqlite3 is not a constructor') || error.message?.includes('better-sqlite3') || error.message?.includes('could not run migrations');
24
- if (isSqliteError) {
25
- const isNpx = process.env.npm_config_user_agent?.includes('npx') || process.cwd().includes('_npx');
26
- if (isNpx) {
27
- console.error('\n⚠️ NPX LIMITATION DETECTED\n');
28
- console.error('ReasoningBank requires better-sqlite3, which is not available in npx temp directories.\n');
29
- console.error('📚 Solutions:\n');
30
- console.error(' 1. LOCAL INSTALL (Recommended):');
31
- console.error(' npm install && node_modules/.bin/claude-flow memory store "key" "value"\n');
32
- console.error(' 2. USE MCP TOOLS instead:');
33
- console.error(' mcp__claude-flow__memory_usage({ action: "store", key: "test", value: "data" })\n');
34
- console.error(' 3. USE JSON FALLBACK:');
35
- console.error(' npx claude-flow@alpha memory store "key" "value" --basic\n');
36
- console.error('See: docs/MEMORY_COMMAND_FIX.md for details\n');
37
- }
23
+ const isNpx = process.env.npm_config_user_agent?.includes('npx') || process.cwd().includes('_npx');
24
+ if (isSqliteError && isNpx) {
25
+ console.error('\n⚠️ NPX LIMITATION DETECTED\n');
26
+ console.error('ReasoningBank requires better-sqlite3, which is not available in npx temp directories.\n');
27
+ console.error('📚 Solutions:\n');
28
+ console.error(' 1. LOCAL INSTALL (Recommended):');
29
+ console.error(' npm install && node_modules/.bin/claude-flow memory store "key" "value"\n');
30
+ console.error(' 2. USE MCP TOOLS instead:');
31
+ console.error(' mcp__claude-flow__memory_usage({ action: "store", key: "test", value: "data" })\n');
32
+ console.error(' 3. USE JSON FALLBACK (automatic):');
33
+ console.error(' Command will continue with JSON storage...\n');
34
+ console.error('See: docs/MEMORY_COMMAND_FIX.md for details\n');
35
+ return false;
38
36
  }
37
+ console.error('[ReasoningBank] Backend initialization failed:', error);
39
38
  throw new Error(`Failed to initialize ReasoningBank: ${error.message}`);
40
39
  }
41
40
  })();
42
41
  return initPromise;
43
42
  }
44
43
  export async function initializeReasoningBank() {
45
- await ensureInitialized();
46
- return true;
44
+ const result = await ensureInitialized();
45
+ return result;
47
46
  }
48
47
  export async function storeMemory(key, value, options = {}) {
49
48
  await ensureInitialized();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/reasoningbank/reasoningbank-adapter.js"],"sourcesContent":["/**\n * ReasoningBank Adapter for Claude-Flow (Node.js Backend)\n *\n * Uses agentic-flow@1.5.13 Node.js backend with SQLite for persistent storage\n * Provides semantic search via embeddings and MMR ranking\n *\n * Backend: SQLite with better-sqlite3\n * Features: Persistent storage, semantic search, memory consolidation\n */\n\nimport * as ReasoningBank from 'agentic-flow/reasoningbank';\nimport { v4 as uuidv4 } from 'uuid';\n\n// Backend instance (singleton)\nlet backendInitialized = false;\nlet initPromise = null;\n\n// Query result cache (LRU)\nconst queryCache = new Map();\nconst CACHE_SIZE = 100;\nconst CACHE_TTL = 60000; // 60 seconds\n\n/**\n * Initialize ReasoningBank Node.js backend\n * @returns {Promise<boolean>}\n */\nasync function ensureInitialized() {\n if (backendInitialized) {\n return true;\n }\n\n if (initPromise) {\n return initPromise;\n }\n\n initPromise = (async () => {\n try {\n // Initialize Node.js backend with SQLite database\n await ReasoningBank.initialize();\n backendInitialized = true;\n console.log('[ReasoningBank] Node.js backend initialized successfully');\n return true;\n } catch (error) {\n console.error('[ReasoningBank] Backend initialization failed:', error);\n\n // Check if this is the better-sqlite3 missing error (npx issue)\n const isSqliteError = error.message?.includes('BetterSqlite3 is not a constructor') ||\n error.message?.includes('better-sqlite3') ||\n error.message?.includes('could not run migrations');\n\n if (isSqliteError) {\n const isNpx = process.env.npm_config_user_agent?.includes('npx') ||\n process.cwd().includes('_npx');\n\n if (isNpx) {\n console.error('\\n⚠️ NPX LIMITATION DETECTED\\n');\n console.error('ReasoningBank requires better-sqlite3, which is not available in npx temp directories.\\n');\n console.error('📚 Solutions:\\n');\n console.error(' 1. LOCAL INSTALL (Recommended):');\n console.error(' npm install && node_modules/.bin/claude-flow memory store \"key\" \"value\"\\n');\n console.error(' 2. USE MCP TOOLS instead:');\n console.error(' mcp__claude-flow__memory_usage({ action: \"store\", key: \"test\", value: \"data\" })\\n');\n console.error(' 3. USE JSON FALLBACK:');\n console.error(' npx claude-flow@alpha memory store \"key\" \"value\" --basic\\n');\n console.error('See: docs/MEMORY_COMMAND_FIX.md for details\\n');\n }\n }\n\n throw new Error(`Failed to initialize ReasoningBank: ${error.message}`);\n }\n })();\n\n return initPromise;\n}\n\n/**\n * Initialize ReasoningBank database (Node.js version)\n */\nexport async function initializeReasoningBank() {\n // Initialize the Node.js backend\n await ensureInitialized();\n return true;\n}\n\n/**\n * Store a memory in ReasoningBank (Node.js backend with SQLite)\n *\n * Maps claude-flow memory model to ReasoningBank pattern model:\n * - key -> title\n * - value -> content (searchable text)\n * - namespace -> domain\n * - confidence -> confidence score\n */\nexport async function storeMemory(key, value, options = {}) {\n await ensureInitialized();\n\n try {\n const memoryId = options.id || uuidv4();\n\n // Map our memory model to ReasoningBank pattern model\n const memory = {\n id: memoryId,\n type: 'reasoning_memory',\n pattern_data: {\n title: key,\n content: value,\n domain: options.namespace || 'default',\n agent: options.agent || 'memory-agent',\n task_type: options.type || 'fact',\n // Store original values for compatibility\n original_key: key,\n original_value: value,\n namespace: options.namespace || 'default'\n },\n confidence: options.confidence || 0.8,\n usage_count: 0\n };\n\n // Store memory using Node.js backend\n ReasoningBank.db.upsertMemory(memory);\n\n // Generate and store embedding for semantic search\n try {\n const embedding = await ReasoningBank.computeEmbedding(value);\n ReasoningBank.db.upsertEmbedding({\n id: memoryId,\n model: 'text-embedding-3-small', // Default model\n dims: embedding.length,\n vector: embedding\n });\n } catch (embeddingError) {\n console.warn('[ReasoningBank] Failed to generate embedding:', embeddingError.message);\n // Continue without embedding - memory is still stored\n }\n\n // Invalidate query cache when new memory is added\n queryCache.clear();\n\n return memoryId;\n } catch (error) {\n console.error('[ReasoningBank] storeMemory failed:', error);\n throw new Error(`Failed to store memory: ${error.message}`);\n }\n}\n\n/**\n * Query memories from ReasoningBank (Node.js backend with semantic search)\n *\n * Uses retrieveMemories for semantic search via embeddings and MMR ranking\n * Fallback to database query if semantic search fails\n */\nexport async function queryMemories(searchQuery, options = {}) {\n // Check cache first\n const cached = getCachedQuery(searchQuery, options);\n if (cached) {\n return cached;\n }\n\n await ensureInitialized();\n const limit = options.limit || 10;\n // Accept both 'namespace' and 'domain' for compatibility\n const namespace = options.namespace || options.domain || 'default';\n\n try {\n // Try semantic search first using retrieveMemories\n const results = await ReasoningBank.retrieveMemories(searchQuery, {\n domain: namespace,\n agent: options.agent || 'query-agent',\n k: limit,\n minConfidence: options.minConfidence || 0.3\n });\n\n // Map backend results to our memory format\n // retrieveMemories returns: { id, title, content, description, score, components }\n const memories = results.map(memory => ({\n id: memory.id,\n key: memory.title || 'unknown',\n value: memory.content || memory.description || '',\n namespace: namespace, // Use the namespace from our query\n confidence: memory.components?.reliability || 0.8,\n usage_count: memory.usage_count || 0,\n created_at: memory.created_at || new Date().toISOString(),\n score: memory.score || 0,\n // Include original pattern for debugging\n _pattern: memory\n }));\n\n // If no results, try direct database query as fallback\n if (memories.length === 0) {\n console.warn('[ReasoningBank] Semantic search returned 0 results, trying database fallback');\n const fallbackResults = ReasoningBank.db.fetchMemoryCandidates({\n domain: namespace,\n minConfidence: options.minConfidence || 0.3\n });\n\n const fallbackMemories = fallbackResults.slice(0, limit).map(memory => ({\n id: memory.id,\n key: memory.pattern_data?.title || memory.pattern_data?.original_key || 'unknown',\n value: memory.pattern_data?.content || memory.pattern_data?.original_value || '',\n namespace: memory.pattern_data?.domain || memory.pattern_data?.namespace || 'default',\n confidence: memory.confidence || 0.8,\n usage_count: memory.usage_count || 0,\n created_at: memory.created_at || new Date().toISOString()\n }));\n\n // Cache and return fallback results\n setCachedQuery(searchQuery, options, fallbackMemories);\n return fallbackMemories;\n }\n\n // Cache successful results\n setCachedQuery(searchQuery, options, memories);\n return memories;\n } catch (error) {\n console.warn('[ReasoningBank] Query failed, trying database fallback:', error.message);\n\n try {\n // Final fallback: direct database query\n const fallbackResults = ReasoningBank.db.fetchMemoryCandidates({\n domain: namespace,\n minConfidence: options.minConfidence || 0.3\n });\n\n const fallbackMemories = fallbackResults.slice(0, limit).map(memory => ({\n id: memory.id,\n key: memory.pattern_data?.title || 'unknown',\n value: memory.pattern_data?.content || '',\n namespace: memory.pattern_data?.domain || 'default',\n confidence: memory.confidence || 0.8,\n usage_count: memory.usage_count || 0,\n created_at: memory.created_at || new Date().toISOString()\n }));\n\n setCachedQuery(searchQuery, options, fallbackMemories);\n return fallbackMemories;\n } catch (fallbackError) {\n console.error('[ReasoningBank] All query methods failed:', fallbackError);\n return [];\n }\n }\n}\n\n/**\n * List all memories (using Node.js backend database query)\n */\nexport async function listMemories(options = {}) {\n await ensureInitialized();\n const limit = options.limit || 10;\n const namespace = options.namespace;\n\n try {\n let memories;\n\n if (namespace && namespace !== 'default') {\n // Filter by namespace/domain\n const allMemories = ReasoningBank.db.getAllActiveMemories();\n memories = allMemories\n .filter(m => m.pattern_data?.domain === namespace)\n .slice(0, limit);\n } else {\n // Get all active memories\n memories = ReasoningBank.db.getAllActiveMemories().slice(0, limit);\n }\n\n return memories.map(memory => ({\n id: memory.id,\n key: memory.pattern_data?.title || memory.pattern_data?.original_key || 'unknown',\n value: memory.pattern_data?.content || memory.pattern_data?.original_value || '',\n namespace: memory.pattern_data?.domain || memory.pattern_data?.namespace || 'default',\n confidence: memory.confidence || 0.8,\n usage_count: memory.usage_count || 0,\n created_at: memory.created_at || new Date().toISOString()\n }));\n } catch (error) {\n console.error('[ReasoningBank] listMemories failed:', error);\n return [];\n }\n}\n\n/**\n * Get ReasoningBank statistics (Node.js backend)\n */\nexport async function getStatus() {\n await ensureInitialized();\n\n try {\n const db = ReasoningBank.db.getDb();\n\n // Count patterns\n const patterns = db.prepare(\"SELECT COUNT(*) as count FROM patterns WHERE type = 'reasoning_memory'\").get();\n const embeddings = db.prepare(\"SELECT COUNT(*) as count FROM pattern_embeddings\").get();\n const trajectories = db.prepare(\"SELECT COUNT(*) as count FROM task_trajectories\").get();\n const links = db.prepare(\"SELECT COUNT(*) as count FROM pattern_links\").get();\n\n // Get average confidence\n const avgConf = db.prepare(\"SELECT AVG(confidence) as avg FROM patterns WHERE type = 'reasoning_memory'\").get();\n\n // Count unique domains\n const domains = db.prepare(\"SELECT COUNT(DISTINCT json_extract(pattern_data, '$.domain')) as count FROM patterns WHERE type = 'reasoning_memory'\").get();\n\n return {\n total_memories: patterns.count || 0,\n total_categories: domains.count || 0,\n storage_backend: 'SQLite (Node.js)',\n database_path: process.env.CLAUDE_FLOW_DB_PATH || '.swarm/memory.db',\n performance: 'SQLite with persistent storage',\n avg_confidence: avgConf.avg || 0.8,\n total_embeddings: embeddings.count || 0,\n total_trajectories: trajectories.count || 0,\n total_links: links.count || 0\n };\n } catch (error) {\n console.error('[ReasoningBank] getStatus failed:', error);\n return {\n total_memories: 0,\n error: error.message\n };\n }\n}\n\n/**\n * Check which ReasoningBank tables are present (Node.js backend)\n */\nexport async function checkReasoningBankTables() {\n try {\n await ensureInitialized();\n const db = ReasoningBank.db.getDb();\n\n const tables = db.prepare(\"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'pattern%'\").all();\n const tableNames = tables.map(t => t.name);\n\n const requiredTables = ['patterns', 'pattern_embeddings', 'pattern_links', 'task_trajectories'];\n const missingTables = requiredTables.filter(t => !tableNames.includes(t));\n\n return {\n exists: true,\n existingTables: tableNames,\n missingTables: missingTables,\n requiredTables: requiredTables,\n backend: 'SQLite (Node.js)',\n note: missingTables.length > 0 ? 'Some tables are missing - run migrations' : 'All tables present'\n };\n } catch (error) {\n return {\n exists: false,\n existingTables: [],\n missingTables: [],\n requiredTables: [],\n error: error.message\n };\n }\n}\n\n/**\n * Migrate existing database (Node.js backend - run migrations)\n */\nexport async function migrateReasoningBank() {\n try {\n await ReasoningBank.db.runMigrations();\n\n return {\n success: true,\n message: 'Database migrations completed successfully',\n migrated: true,\n database_path: process.env.CLAUDE_FLOW_DB_PATH || '.swarm/memory.db'\n };\n } catch (error) {\n return {\n success: false,\n message: `Migration failed: ${error.message}`,\n error: error.message\n };\n }\n}\n\n/**\n * Get cached query results\n */\nfunction getCachedQuery(searchQuery, options) {\n const cacheKey = JSON.stringify({ searchQuery, options });\n const cached = queryCache.get(cacheKey);\n\n if (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n return cached.results;\n }\n\n return null;\n}\n\n/**\n * Set cached query results (LRU eviction)\n */\nfunction setCachedQuery(searchQuery, options, results) {\n const cacheKey = JSON.stringify({ searchQuery, options });\n\n // LRU eviction\n if (queryCache.size >= CACHE_SIZE) {\n const firstKey = queryCache.keys().next().value;\n queryCache.delete(firstKey);\n }\n\n queryCache.set(cacheKey, {\n results,\n timestamp: Date.now()\n });\n}\n\n/**\n * Close database connection and cleanup resources\n * Should be called when done with ReasoningBank operations\n */\nexport function cleanup() {\n try {\n if (backendInitialized) {\n // Clear embedding cache (prevents memory leaks)\n ReasoningBank.clearEmbeddingCache();\n\n // Close database connection\n ReasoningBank.db.closeDb();\n backendInitialized = false;\n initPromise = null;\n console.log('[ReasoningBank] Database connection closed');\n }\n } catch (error) {\n console.error('[ReasoningBank] Cleanup failed:', error.message);\n }\n}\n"],"names":["ReasoningBank","v4","uuidv4","backendInitialized","initPromise","queryCache","Map","CACHE_SIZE","CACHE_TTL","ensureInitialized","initialize","console","log","error","isSqliteError","message","includes","isNpx","process","env","npm_config_user_agent","cwd","Error","initializeReasoningBank","storeMemory","key","value","options","memoryId","id","memory","type","pattern_data","title","content","domain","namespace","agent","task_type","original_key","original_value","confidence","usage_count","db","upsertMemory","embedding","computeEmbedding","upsertEmbedding","model","dims","length","vector","embeddingError","warn","clear","queryMemories","searchQuery","cached","getCachedQuery","limit","results","retrieveMemories","k","minConfidence","memories","map","description","components","reliability","created_at","Date","toISOString","score","_pattern","fallbackResults","fetchMemoryCandidates","fallbackMemories","slice","setCachedQuery","fallbackError","listMemories","allMemories","getAllActiveMemories","filter","m","getStatus","getDb","patterns","prepare","get","embeddings","trajectories","links","avgConf","domains","total_memories","count","total_categories","storage_backend","database_path","CLAUDE_FLOW_DB_PATH","performance","avg_confidence","avg","total_embeddings","total_trajectories","total_links","checkReasoningBankTables","tables","all","tableNames","t","name","requiredTables","missingTables","exists","existingTables","backend","note","migrateReasoningBank","runMigrations","success","migrated","cacheKey","JSON","stringify","now","timestamp","size","firstKey","keys","next","delete","set","cleanup","clearEmbeddingCache","closeDb"],"mappings":"AAUA,YAAYA,mBAAmB,6BAA6B;AAC5D,SAASC,MAAMC,MAAM,QAAQ,OAAO;AAGpC,IAAIC,qBAAqB;AACzB,IAAIC,cAAc;AAGlB,MAAMC,aAAa,IAAIC;AACvB,MAAMC,aAAa;AACnB,MAAMC,YAAY;AAMlB,eAAeC;IACb,IAAIN,oBAAoB;QACtB,OAAO;IACT;IAEA,IAAIC,aAAa;QACf,OAAOA;IACT;IAEAA,cAAc,AAAC,CAAA;QACb,IAAI;YAEF,MAAMJ,cAAcU,UAAU;YAC9BP,qBAAqB;YACrBQ,QAAQC,GAAG,CAAC;YACZ,OAAO;QACT,EAAE,OAAOC,OAAO;YACdF,QAAQE,KAAK,CAAC,kDAAkDA;YAGhE,MAAMC,gBAAgBD,MAAME,OAAO,EAAEC,SAAS,yCACzBH,MAAME,OAAO,EAAEC,SAAS,qBACxBH,MAAME,OAAO,EAAEC,SAAS;YAE7C,IAAIF,eAAe;gBACjB,MAAMG,QAAQC,QAAQC,GAAG,CAACC,qBAAqB,EAAEJ,SAAS,UAC5CE,QAAQG,GAAG,GAAGL,QAAQ,CAAC;gBAErC,IAAIC,OAAO;oBACTN,QAAQE,KAAK,CAAC;oBACdF,QAAQE,KAAK,CAAC;oBACdF,QAAQE,KAAK,CAAC;oBACdF,QAAQE,KAAK,CAAC;oBACdF,QAAQE,KAAK,CAAC;oBACdF,QAAQE,KAAK,CAAC;oBACdF,QAAQE,KAAK,CAAC;oBACdF,QAAQE,KAAK,CAAC;oBACdF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AejF,QAAQC,GAAG,CAACiF,mBAAmB,IAAI;QACpD;IACF,EAAE,OAAOvF,OAAO;QACd,OAAO;YACL4G,SAAS;YACT1G,SAAS,CAAC,kBAAkB,EAAEF,MAAME,OAAO,EAAE;YAC7CF,OAAOA,MAAME,OAAO;QACtB;IACF;AACF;AAKA,SAAS2C,eAAeF,WAAW,EAAE7B,OAAO;IAC1C,MAAMgG,WAAWC,KAAKC,SAAS,CAAC;QAAErE;QAAa7B;IAAQ;IACvD,MAAM8B,SAASpD,WAAWoF,GAAG,CAACkC;IAE9B,IAAIlE,UAAUa,KAAKwD,GAAG,KAAKrE,OAAOsE,SAAS,GAAGvH,WAAW;QACvD,OAAOiD,OAAOG,OAAO;IACvB;IAEA,OAAO;AACT;AAKA,SAASkB,eAAetB,WAAW,EAAE7B,OAAO,EAAEiC,OAAO;IACnD,MAAM+D,WAAWC,KAAKC,SAAS,CAAC;QAAErE;QAAa7B;IAAQ;IAGvD,IAAItB,WAAW2H,IAAI,IAAIzH,YAAY;QACjC,MAAM0H,WAAW5H,WAAW6H,IAAI,GAAGC,IAAI,GAAGzG,KAAK;QAC/CrB,WAAW+H,MAAM,CAACH;IACpB;IAEA5H,WAAWgI,GAAG,CAACV,UAAU;QACvB/D;QACAmE,WAAWzD,KAAKwD,GAAG;IACrB;AACF;AAMA,OAAO,SAASQ;IACd,IAAI;QACF,IAAInI,oBAAoB;YAEtBH,cAAcuI,mBAAmB;YAGjCvI,cAAc2C,EAAE,CAAC6F,OAAO;YACxBrI,qBAAqB;YACrBC,cAAc;YACdO,QAAQC,GAAG,CAAC;QACd;IACF,EAAE,OAAOC,OAAO;QACdF,QAAQE,KAAK,CAAC,mCAAmCA,MAAME,OAAO;IAChE;AACF"}
1
+ {"version":3,"sources":["../../../src/reasoningbank/reasoningbank-adapter.js"],"sourcesContent":["/**\n * ReasoningBank Adapter for Claude-Flow (Node.js Backend)\n *\n * Uses agentic-flow@1.5.13 Node.js backend with SQLite for persistent storage\n * Provides semantic search via embeddings and MMR ranking\n *\n * Backend: SQLite with better-sqlite3\n * Features: Persistent storage, semantic search, memory consolidation\n */\n\nimport * as ReasoningBank from 'agentic-flow/reasoningbank';\nimport { v4 as uuidv4 } from 'uuid';\n\n// Backend instance (singleton)\nlet backendInitialized = false;\nlet initPromise = null;\n\n// Query result cache (LRU)\nconst queryCache = new Map();\nconst CACHE_SIZE = 100;\nconst CACHE_TTL = 60000; // 60 seconds\n\n/**\n * Initialize ReasoningBank Node.js backend\n * @returns {Promise<boolean>}\n */\nasync function ensureInitialized() {\n if (backendInitialized) {\n return true;\n }\n\n if (initPromise) {\n return initPromise;\n }\n\n initPromise = (async () => {\n try {\n // Initialize Node.js backend with SQLite database\n await ReasoningBank.initialize();\n backendInitialized = true;\n console.log('[ReasoningBank] Node.js backend initialized successfully');\n return true;\n } catch (error) {\n // Check if this is the better-sqlite3 missing error (npx issue)\n const isSqliteError = error.message?.includes('BetterSqlite3 is not a constructor') ||\n error.message?.includes('better-sqlite3') ||\n error.message?.includes('could not run migrations');\n const isNpx = process.env.npm_config_user_agent?.includes('npx') ||\n process.cwd().includes('_npx');\n\n if (isSqliteError && isNpx) {\n // NPX limitation - show helpful message but DON'T throw\n // This allows the command to fall back to JSON mode\n console.error('\\n⚠️ NPX LIMITATION DETECTED\\n');\n console.error('ReasoningBank requires better-sqlite3, which is not available in npx temp directories.\\n');\n console.error('📚 Solutions:\\n');\n console.error(' 1. LOCAL INSTALL (Recommended):');\n console.error(' npm install && node_modules/.bin/claude-flow memory store \"key\" \"value\"\\n');\n console.error(' 2. USE MCP TOOLS instead:');\n console.error(' mcp__claude-flow__memory_usage({ action: \"store\", key: \"test\", value: \"data\" })\\n');\n console.error(' 3. USE JSON FALLBACK (automatic):');\n console.error(' Command will continue with JSON storage...\\n');\n console.error('See: docs/MEMORY_COMMAND_FIX.md for details\\n');\n\n // Return false to signal initialization failed but allow fallback\n return false;\n }\n\n // Not npx or not SQLite error - log and throw\n console.error('[ReasoningBank] Backend initialization failed:', error);\n throw new Error(`Failed to initialize ReasoningBank: ${error.message}`);\n }\n })();\n\n return initPromise;\n}\n\n/**\n * Initialize ReasoningBank database (Node.js version)\n * Returns true if initialized, false if failed (allows fallback)\n */\nexport async function initializeReasoningBank() {\n // Initialize the Node.js backend\n const result = await ensureInitialized();\n return result;\n}\n\n/**\n * Store a memory in ReasoningBank (Node.js backend with SQLite)\n *\n * Maps claude-flow memory model to ReasoningBank pattern model:\n * - key -> title\n * - value -> content (searchable text)\n * - namespace -> domain\n * - confidence -> confidence score\n */\nexport async function storeMemory(key, value, options = {}) {\n await ensureInitialized();\n\n try {\n const memoryId = options.id || uuidv4();\n\n // Map our memory model to ReasoningBank pattern model\n const memory = {\n id: memoryId,\n type: 'reasoning_memory',\n pattern_data: {\n title: key,\n content: value,\n domain: options.namespace || 'default',\n agent: options.agent || 'memory-agent',\n task_type: options.type || 'fact',\n // Store original values for compatibility\n original_key: key,\n original_value: value,\n namespace: options.namespace || 'default'\n },\n confidence: options.confidence || 0.8,\n usage_count: 0\n };\n\n // Store memory using Node.js backend\n ReasoningBank.db.upsertMemory(memory);\n\n // Generate and store embedding for semantic search\n try {\n const embedding = await ReasoningBank.computeEmbedding(value);\n ReasoningBank.db.upsertEmbedding({\n id: memoryId,\n model: 'text-embedding-3-small', // Default model\n dims: embedding.length,\n vector: embedding\n });\n } catch (embeddingError) {\n console.warn('[ReasoningBank] Failed to generate embedding:', embeddingError.message);\n // Continue without embedding - memory is still stored\n }\n\n // Invalidate query cache when new memory is added\n queryCache.clear();\n\n return memoryId;\n } catch (error) {\n console.error('[ReasoningBank] storeMemory failed:', error);\n throw new Error(`Failed to store memory: ${error.message}`);\n }\n}\n\n/**\n * Query memories from ReasoningBank (Node.js backend with semantic search)\n *\n * Uses retrieveMemories for semantic search via embeddings and MMR ranking\n * Fallback to database query if semantic search fails\n */\nexport async function queryMemories(searchQuery, options = {}) {\n // Check cache first\n const cached = getCachedQuery(searchQuery, options);\n if (cached) {\n return cached;\n }\n\n await ensureInitialized();\n const limit = options.limit || 10;\n // Accept both 'namespace' and 'domain' for compatibility\n const namespace = options.namespace || options.domain || 'default';\n\n try {\n // Try semantic search first using retrieveMemories\n const results = await ReasoningBank.retrieveMemories(searchQuery, {\n domain: namespace,\n agent: options.agent || 'query-agent',\n k: limit,\n minConfidence: options.minConfidence || 0.3\n });\n\n // Map backend results to our memory format\n // retrieveMemories returns: { id, title, content, description, score, components }\n const memories = results.map(memory => ({\n id: memory.id,\n key: memory.title || 'unknown',\n value: memory.content || memory.description || '',\n namespace: namespace, // Use the namespace from our query\n confidence: memory.components?.reliability || 0.8,\n usage_count: memory.usage_count || 0,\n created_at: memory.created_at || new Date().toISOString(),\n score: memory.score || 0,\n // Include original pattern for debugging\n _pattern: memory\n }));\n\n // If no results, try direct database query as fallback\n if (memories.length === 0) {\n console.warn('[ReasoningBank] Semantic search returned 0 results, trying database fallback');\n const fallbackResults = ReasoningBank.db.fetchMemoryCandidates({\n domain: namespace,\n minConfidence: options.minConfidence || 0.3\n });\n\n const fallbackMemories = fallbackResults.slice(0, limit).map(memory => ({\n id: memory.id,\n key: memory.pattern_data?.title || memory.pattern_data?.original_key || 'unknown',\n value: memory.pattern_data?.content || memory.pattern_data?.original_value || '',\n namespace: memory.pattern_data?.domain || memory.pattern_data?.namespace || 'default',\n confidence: memory.confidence || 0.8,\n usage_count: memory.usage_count || 0,\n created_at: memory.created_at || new Date().toISOString()\n }));\n\n // Cache and return fallback results\n setCachedQuery(searchQuery, options, fallbackMemories);\n return fallbackMemories;\n }\n\n // Cache successful results\n setCachedQuery(searchQuery, options, memories);\n return memories;\n } catch (error) {\n console.warn('[ReasoningBank] Query failed, trying database fallback:', error.message);\n\n try {\n // Final fallback: direct database query\n const fallbackResults = ReasoningBank.db.fetchMemoryCandidates({\n domain: namespace,\n minConfidence: options.minConfidence || 0.3\n });\n\n const fallbackMemories = fallbackResults.slice(0, limit).map(memory => ({\n id: memory.id,\n key: memory.pattern_data?.title || 'unknown',\n value: memory.pattern_data?.content || '',\n namespace: memory.pattern_data?.domain || 'default',\n confidence: memory.confidence || 0.8,\n usage_count: memory.usage_count || 0,\n created_at: memory.created_at || new Date().toISOString()\n }));\n\n setCachedQuery(searchQuery, options, fallbackMemories);\n return fallbackMemories;\n } catch (fallbackError) {\n console.error('[ReasoningBank] All query methods failed:', fallbackError);\n return [];\n }\n }\n}\n\n/**\n * List all memories (using Node.js backend database query)\n */\nexport async function listMemories(options = {}) {\n await ensureInitialized();\n const limit = options.limit || 10;\n const namespace = options.namespace;\n\n try {\n let memories;\n\n if (namespace && namespace !== 'default') {\n // Filter by namespace/domain\n const allMemories = ReasoningBank.db.getAllActiveMemories();\n memories = allMemories\n .filter(m => m.pattern_data?.domain === namespace)\n .slice(0, limit);\n } else {\n // Get all active memories\n memories = ReasoningBank.db.getAllActiveMemories().slice(0, limit);\n }\n\n return memories.map(memory => ({\n id: memory.id,\n key: memory.pattern_data?.title || memory.pattern_data?.original_key || 'unknown',\n value: memory.pattern_data?.content || memory.pattern_data?.original_value || '',\n namespace: memory.pattern_data?.domain || memory.pattern_data?.namespace || 'default',\n confidence: memory.confidence || 0.8,\n usage_count: memory.usage_count || 0,\n created_at: memory.created_at || new Date().toISOString()\n }));\n } catch (error) {\n console.error('[ReasoningBank] listMemories failed:', error);\n return [];\n }\n}\n\n/**\n * Get ReasoningBank statistics (Node.js backend)\n */\nexport async function getStatus() {\n await ensureInitialized();\n\n try {\n const db = ReasoningBank.db.getDb();\n\n // Count patterns\n const patterns = db.prepare(\"SELECT COUNT(*) as count FROM patterns WHERE type = 'reasoning_memory'\").get();\n const embeddings = db.prepare(\"SELECT COUNT(*) as count FROM pattern_embeddings\").get();\n const trajectories = db.prepare(\"SELECT COUNT(*) as count FROM task_trajectories\").get();\n const links = db.prepare(\"SELECT COUNT(*) as count FROM pattern_links\").get();\n\n // Get average confidence\n const avgConf = db.prepare(\"SELECT AVG(confidence) as avg FROM patterns WHERE type = 'reasoning_memory'\").get();\n\n // Count unique domains\n const domains = db.prepare(\"SELECT COUNT(DISTINCT json_extract(pattern_data, '$.domain')) as count FROM patterns WHERE type = 'reasoning_memory'\").get();\n\n return {\n total_memories: patterns.count || 0,\n total_categories: domains.count || 0,\n storage_backend: 'SQLite (Node.js)',\n database_path: process.env.CLAUDE_FLOW_DB_PATH || '.swarm/memory.db',\n performance: 'SQLite with persistent storage',\n avg_confidence: avgConf.avg || 0.8,\n total_embeddings: embeddings.count || 0,\n total_trajectories: trajectories.count || 0,\n total_links: links.count || 0\n };\n } catch (error) {\n console.error('[ReasoningBank] getStatus failed:', error);\n return {\n total_memories: 0,\n error: error.message\n };\n }\n}\n\n/**\n * Check which ReasoningBank tables are present (Node.js backend)\n */\nexport async function checkReasoningBankTables() {\n try {\n await ensureInitialized();\n const db = ReasoningBank.db.getDb();\n\n const tables = db.prepare(\"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'pattern%'\").all();\n const tableNames = tables.map(t => t.name);\n\n const requiredTables = ['patterns', 'pattern_embeddings', 'pattern_links', 'task_trajectories'];\n const missingTables = requiredTables.filter(t => !tableNames.includes(t));\n\n return {\n exists: true,\n existingTables: tableNames,\n missingTables: missingTables,\n requiredTables: requiredTables,\n backend: 'SQLite (Node.js)',\n note: missingTables.length > 0 ? 'Some tables are missing - run migrations' : 'All tables present'\n };\n } catch (error) {\n return {\n exists: false,\n existingTables: [],\n missingTables: [],\n requiredTables: [],\n error: error.message\n };\n }\n}\n\n/**\n * Migrate existing database (Node.js backend - run migrations)\n */\nexport async function migrateReasoningBank() {\n try {\n await ReasoningBank.db.runMigrations();\n\n return {\n success: true,\n message: 'Database migrations completed successfully',\n migrated: true,\n database_path: process.env.CLAUDE_FLOW_DB_PATH || '.swarm/memory.db'\n };\n } catch (error) {\n return {\n success: false,\n message: `Migration failed: ${error.message}`,\n error: error.message\n };\n }\n}\n\n/**\n * Get cached query results\n */\nfunction getCachedQuery(searchQuery, options) {\n const cacheKey = JSON.stringify({ searchQuery, options });\n const cached = queryCache.get(cacheKey);\n\n if (cached && Date.now() - cached.timestamp < CACHE_TTL) {\n return cached.results;\n }\n\n return null;\n}\n\n/**\n * Set cached query results (LRU eviction)\n */\nfunction setCachedQuery(searchQuery, options, results) {\n const cacheKey = JSON.stringify({ searchQuery, options });\n\n // LRU eviction\n if (queryCache.size >= CACHE_SIZE) {\n const firstKey = queryCache.keys().next().value;\n queryCache.delete(firstKey);\n }\n\n queryCache.set(cacheKey, {\n results,\n timestamp: Date.now()\n });\n}\n\n/**\n * Close database connection and cleanup resources\n * Should be called when done with ReasoningBank operations\n */\nexport function cleanup() {\n try {\n if (backendInitialized) {\n // Clear embedding cache (prevents memory leaks)\n ReasoningBank.clearEmbeddingCache();\n\n // Close database connection\n ReasoningBank.db.closeDb();\n backendInitialized = false;\n initPromise = null;\n console.log('[ReasoningBank] Database connection closed');\n }\n } catch (error) {\n console.error('[ReasoningBank] Cleanup failed:', error.message);\n }\n}\n"],"names":["ReasoningBank","v4","uuidv4","backendInitialized","initPromise","queryCache","Map","CACHE_SIZE","CACHE_TTL","ensureInitialized","initialize","console","log","error","isSqliteError","message","includes","isNpx","process","env","npm_config_user_agent","cwd","Error","initializeReasoningBank","result","storeMemory","key","value","options","memoryId","id","memory","type","pattern_data","title","content","domain","namespace","agent","task_type","original_key","original_value","confidence","usage_count","db","upsertMemory","embedding","computeEmbedding","upsertEmbedding","model","dims","length","vector","embeddingError","warn","clear","queryMemories","searchQuery","cached","getCachedQuery","limit","results","retrieveMemories","k","minConfidence","memories","map","description","components","reliability","created_at","Date","toISOString","score","_pattern","fallbackResults","fetchMemoryCandidates","fallbackMemories","slice","setCachedQuery","fallbackError","listMemories","allMemories","getAllActiveMemories","filter","m","getStatus","getDb","patterns","prepare","get","embeddings","trajectories","links","avgConf","domains","total_memories","count","total_categories","storage_backend","database_path","CLAUDE_FLOW_DB_PATH","performance","avg_confidence","avg","total_embeddings","total_trajectories","total_links","checkReasoningBankTables","tables","all","tableNames","t","name","requiredTables","missingTables","exists","existingTables","backend","note","migrateReasoningBank","runMigrations","success","migrated","cacheKey","JSON","stringify","now","timestamp","size","firstKey","keys","next","delete","set","cleanup","clearEmbeddingCache","closeDb"],"mappings":"AAUA,YAAYA,mBAAmB,6BAA6B;AAC5D,SAASC,MAAMC,MAAM,QAAQ,OAAO;AAGpC,IAAIC,qBAAqB;AACzB,IAAIC,cAAc;AAGlB,MAAMC,aAAa,IAAIC;AACvB,MAAMC,aAAa;AACnB,MAAMC,YAAY;AAMlB,eAAeC;IACb,IAAIN,oBAAoB;QACtB,OAAO;IACT;IAEA,IAAIC,aAAa;QACf,OAAOA;IACT;IAEAA,cAAc,AAAC,CAAA;QACb,IAAI;YAEF,MAAMJ,cAAcU,UAAU;YAC9BP,qBAAqB;YACrBQ,QAAQC,GAAG,CAAC;YACZ,OAAO;QACT,EAAE,OAAOC,OAAO;YAEd,MAAMC,gBAAgBD,MAAME,OAAO,EAAEC,SAAS,yCACzBH,MAAME,OAAO,EAAEC,SAAS,qBACxBH,MAAME,OAAO,EAAEC,SAAS;YAC7C,MAAMC,QAAQC,QAAQC,GAAG,CAACC,qBAAqB,EAAEJ,SAAS,UAC5CE,QAAQG,GAAG,GAAGL,QAAQ,CAAC;YAErC,IAAIF,iBAAiBG,OAAO;gBAG1BN,QAAQE,KAAK,CAAC;gBACdF,QAAQE,KAAK,CAAC;gBACdF,QAAQE,KAAK,CAAC;gBACdF,QAAQE,KAAK,CAAC;gBACdF,QAAQE,KAAK,CAAC;gBACdF,QAAQE,KAAK,CAAC;gBACdF,QAAQE,KAAK,CAAC;gBACdF,QAAQE,KAAK,CAAC;gBACdF,QAAQE,KAAK,CAAC;gBACdF,QAAQE,KAAK,CAAC;gBAGd,OAAO;YACT;YAGAF,QAAQE,KAAK,CAAC,kDAAkDA;YAChE,MAAM,IAAIS,MAAM,CAAC,oCAAoC,EAAET,MAAME,OAAO,EAAE;QACxE;IACF,CAAA;IAEA,OAAOX;AACT;AAMA,OAAO,eAAemB;IAEpB,MAAMC,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AO;QACtB;IACF;AACF;AAKA,SAAS4C,eAAeF,WAAW,EAAE7B,OAAO;IAC1C,MAAMgG,WAAWC,KAAKC,SAAS,CAAC;QAAErE;QAAa7B;IAAQ;IACvD,MAAM8B,SAASrD,WAAWqF,GAAG,CAACkC;IAE9B,IAAIlE,UAAUa,KAAKwD,GAAG,KAAKrE,OAAOsE,SAAS,GAAGxH,WAAW;QACvD,OAAOkD,OAAOG,OAAO;IACvB;IAEA,OAAO;AACT;AAKA,SAASkB,eAAetB,WAAW,EAAE7B,OAAO,EAAEiC,OAAO;IACnD,MAAM+D,WAAWC,KAAKC,SAAS,CAAC;QAAErE;QAAa7B;IAAQ;IAGvD,IAAIvB,WAAW4H,IAAI,IAAI1H,YAAY;QACjC,MAAM2H,WAAW7H,WAAW8H,IAAI,GAAGC,IAAI,GAAGzG,KAAK;QAC/CtB,WAAWgI,MAAM,CAACH;IACpB;IAEA7H,WAAWiI,GAAG,CAACV,UAAU;QACvB/D;QACAmE,WAAWzD,KAAKwD,GAAG;IACrB;AACF;AAMA,OAAO,SAASQ;IACd,IAAI;QACF,IAAIpI,oBAAoB;YAEtBH,cAAcwI,mBAAmB;YAGjCxI,cAAc4C,EAAE,CAAC6F,OAAO;YACxBtI,qBAAqB;YACrBC,cAAc;YACdO,QAAQC,GAAG,CAAC;QACd;IACF,EAAE,OAAOC,OAAO;QACdF,QAAQE,KAAK,CAAC,mCAAmCA,MAAME,OAAO;IAChE;AACF"}
@@ -1,7 +1,7 @@
1
1
  {
2
- "startTime": 1760925323833,
3
- "sessionId": "session-1760925323833",
4
- "lastActivity": 1760925323833,
2
+ "startTime": 1761424134795,
3
+ "sessionId": "session-1761424134795",
4
+ "lastActivity": 1761424134795,
5
5
  "sessionDuration": 0,
6
6
  "totalTasks": 1,
7
7
  "successfulTasks": 1,
@@ -1,10 +1,10 @@
1
1
  [
2
2
  {
3
- "id": "cmd-hooks-1760925323933",
3
+ "id": "cmd-hooks-1761424134902",
4
4
  "type": "hooks",
5
5
  "success": true,
6
- "duration": 7.107392000000004,
7
- "timestamp": 1760925323940,
6
+ "duration": 10.192307000000028,
7
+ "timestamp": 1761424134913,
8
8
  "metadata": {}
9
9
  }
10
10
  ]
@@ -0,0 +1,20 @@
1
+ FROM node:20-slim
2
+
3
+ # Install basic tools
4
+ RUN apt-get update && apt-get install -y \
5
+ curl \
6
+ git \
7
+ && rm -rf /var/lib/apt/lists/*
8
+
9
+ # Create working directory
10
+ WORKDIR /test
11
+
12
+ # Copy test script
13
+ COPY test-npx-memory.sh /test/test-npx-memory.sh
14
+ RUN chmod +x /test/test-npx-memory.sh
15
+
16
+ # Set environment to ensure we're testing npx behavior
17
+ ENV NPM_CONFIG_LOGLEVEL=warn
18
+
19
+ # Run tests
20
+ CMD ["/test/test-npx-memory.sh"]
@@ -0,0 +1,11 @@
1
+ {
2
+ "default": [
3
+ {
4
+ "key": "test-api",
5
+ "value": "REST with JWT",
6
+ "namespace": "default",
7
+ "timestamp": 1761424106926,
8
+ "redacted": false
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,84 @@
1
+ #!/bin/bash
2
+ # Test npx memory commands in Docker to validate v2.7.17 fix
3
+ # This simulates a clean remote environment without local dependencies
4
+
5
+ set -e
6
+
7
+ echo "🐳 Testing claude-flow@alpha npx memory commands in Docker"
8
+ echo "============================================================"
9
+ echo ""
10
+
11
+ # Test 1: Version check
12
+ echo "📋 Test 1: Version Check"
13
+ echo "Command: npx claude-flow@alpha --version"
14
+ npx claude-flow@alpha --version
15
+ echo "✅ Version check passed"
16
+ echo ""
17
+
18
+ # Test 2: Memory store (should auto-fallback to JSON)
19
+ echo "📋 Test 2: Memory Store with Auto-Fallback"
20
+ echo "Command: npx claude-flow@alpha memory store 'api-design' 'REST with JWT auth'"
21
+ npx claude-flow@alpha memory store "api-design" "REST with JWT auth" 2>&1 | tee /tmp/store-output.txt
22
+ echo ""
23
+
24
+ # Validate output
25
+ if grep -q "Automatically using JSON fallback" /tmp/store-output.txt; then
26
+ echo "✅ Auto-fallback message detected"
27
+ else
28
+ echo "⚠️ Auto-fallback message NOT found (may be using different mode)"
29
+ fi
30
+
31
+ if grep -q "Stored:" /tmp/store-output.txt || grep -q "✅" /tmp/store-output.txt; then
32
+ echo "✅ Memory store succeeded"
33
+ else
34
+ echo "❌ Memory store FAILED"
35
+ exit 1
36
+ fi
37
+ echo ""
38
+
39
+ # Test 3: Memory query
40
+ echo "📋 Test 3: Memory Query"
41
+ echo "Command: npx claude-flow@alpha memory query 'authentication'"
42
+ npx claude-flow@alpha memory query "authentication" 2>&1 | tee /tmp/query-output.txt
43
+ echo ""
44
+
45
+ # Validate query output
46
+ if grep -q "api-design" /tmp/query-output.txt || grep -q "REST" /tmp/query-output.txt; then
47
+ echo "✅ Memory query found stored data"
48
+ else
49
+ echo "⚠️ Memory query did not find data (may be namespace issue)"
50
+ fi
51
+ echo ""
52
+
53
+ # Test 4: Memory stats
54
+ echo "📋 Test 4: Memory Statistics"
55
+ echo "Command: npx claude-flow@alpha memory stats"
56
+ npx claude-flow@alpha memory stats 2>&1 | tee /tmp/stats-output.txt
57
+ echo ""
58
+
59
+ if grep -q "Total Entries:" /tmp/stats-output.txt; then
60
+ echo "✅ Memory stats succeeded"
61
+ else
62
+ echo "❌ Memory stats FAILED"
63
+ exit 1
64
+ fi
65
+ echo ""
66
+
67
+ # Test 5: Memory list
68
+ echo "📋 Test 5: Memory List"
69
+ echo "Command: npx claude-flow@alpha memory list"
70
+ npx claude-flow@alpha memory list 2>&1
71
+ echo "✅ Memory list succeeded"
72
+ echo ""
73
+
74
+ echo "============================================================"
75
+ echo "✅ ALL TESTS PASSED!"
76
+ echo ""
77
+ echo "Summary:"
78
+ echo "- Version check: ✅"
79
+ echo "- Memory store with auto-fallback: ✅"
80
+ echo "- Memory query: ✅"
81
+ echo "- Memory stats: ✅"
82
+ echo "- Memory list: ✅"
83
+ echo ""
84
+ echo "The npx memory command fix in v2.7.17 is working correctly!"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-flow",
3
- "version": "2.7.17",
3
+ "version": "2.7.19",
4
4
  "description": "Enterprise-grade AI agent orchestration with WASM-powered ReasoningBank memory and AgentDB vector database (always uses latest agentic-flow)",
5
5
  "mcpName": "io.github.ruvnet/claude-flow",
6
6
  "main": "cli.mjs",
@@ -418,7 +418,21 @@ async function detectMemoryMode(flags, subArgs) {
418
418
  // Not initialized yet - try to auto-initialize on first use
419
419
  try {
420
420
  const { initializeReasoningBank } = await import('../../reasoningbank/reasoningbank-adapter.js');
421
- await initializeReasoningBank();
421
+ const initialized = await initializeReasoningBank();
422
+
423
+ // Check if initialization succeeded (returns true) or failed (returns false)
424
+ if (!initialized) {
425
+ // Initialization failed but didn't throw - fall back to JSON
426
+ const isNpx = process.env.npm_config_user_agent?.includes('npx') ||
427
+ process.cwd().includes('_npx');
428
+ if (isNpx) {
429
+ console.log('\n✅ Automatically using JSON fallback for this command\n');
430
+ } else {
431
+ printWarning(`⚠️ SQLite unavailable, using JSON fallback`);
432
+ }
433
+ return 'basic';
434
+ }
435
+
422
436
  printInfo('🗄️ Initialized SQLite backend (.swarm/memory.db)');
423
437
  return 'reasoningbank';
424
438
  } catch (error) {
@@ -41,31 +41,33 @@ async function ensureInitialized() {
41
41
  console.log('[ReasoningBank] Node.js backend initialized successfully');
42
42
  return true;
43
43
  } catch (error) {
44
- console.error('[ReasoningBank] Backend initialization failed:', error);
45
-
46
44
  // Check if this is the better-sqlite3 missing error (npx issue)
47
45
  const isSqliteError = error.message?.includes('BetterSqlite3 is not a constructor') ||
48
46
  error.message?.includes('better-sqlite3') ||
49
47
  error.message?.includes('could not run migrations');
50
-
51
- if (isSqliteError) {
52
- const isNpx = process.env.npm_config_user_agent?.includes('npx') ||
53
- process.cwd().includes('_npx');
54
-
55
- if (isNpx) {
56
- console.error('\n⚠️ NPX LIMITATION DETECTED\n');
57
- console.error('ReasoningBank requires better-sqlite3, which is not available in npx temp directories.\n');
58
- console.error('📚 Solutions:\n');
59
- console.error(' 1. LOCAL INSTALL (Recommended):');
60
- console.error(' npm install && node_modules/.bin/claude-flow memory store "key" "value"\n');
61
- console.error(' 2. USE MCP TOOLS instead:');
62
- console.error(' mcp__claude-flow__memory_usage({ action: "store", key: "test", value: "data" })\n');
63
- console.error(' 3. USE JSON FALLBACK:');
64
- console.error(' npx claude-flow@alpha memory store "key" "value" --basic\n');
65
- console.error('See: docs/MEMORY_COMMAND_FIX.md for details\n');
66
- }
48
+ const isNpx = process.env.npm_config_user_agent?.includes('npx') ||
49
+ process.cwd().includes('_npx');
50
+
51
+ if (isSqliteError && isNpx) {
52
+ // NPX limitation - show helpful message but DON'T throw
53
+ // This allows the command to fall back to JSON mode
54
+ console.error('\n⚠️ NPX LIMITATION DETECTED\n');
55
+ console.error('ReasoningBank requires better-sqlite3, which is not available in npx temp directories.\n');
56
+ console.error('📚 Solutions:\n');
57
+ console.error(' 1. LOCAL INSTALL (Recommended):');
58
+ console.error(' npm install && node_modules/.bin/claude-flow memory store "key" "value"\n');
59
+ console.error(' 2. USE MCP TOOLS instead:');
60
+ console.error(' mcp__claude-flow__memory_usage({ action: "store", key: "test", value: "data" })\n');
61
+ console.error(' 3. USE JSON FALLBACK (automatic):');
62
+ console.error(' Command will continue with JSON storage...\n');
63
+ console.error('See: docs/MEMORY_COMMAND_FIX.md for details\n');
64
+
65
+ // Return false to signal initialization failed but allow fallback
66
+ return false;
67
67
  }
68
68
 
69
+ // Not npx or not SQLite error - log and throw
70
+ console.error('[ReasoningBank] Backend initialization failed:', error);
69
71
  throw new Error(`Failed to initialize ReasoningBank: ${error.message}`);
70
72
  }
71
73
  })();
@@ -75,11 +77,12 @@ async function ensureInitialized() {
75
77
 
76
78
  /**
77
79
  * Initialize ReasoningBank database (Node.js version)
80
+ * Returns true if initialized, false if failed (allows fallback)
78
81
  */
79
82
  export async function initializeReasoningBank() {
80
83
  // Initialize the Node.js backend
81
- await ensureInitialized();
82
- return true;
84
+ const result = await ensureInitialized();
85
+ return result;
83
86
  }
84
87
 
85
88
  /**